What is the use of ‘Using’ statement in C#?


The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations.

The main goal is to manage resources and release all the resources automatically.

Let us see an example wherein “A” would print first since the SystemResource is allocated first.

Example

 Live Demo

using System;
using System.Text;

class Demo {
   static void Main() {
      using (SystemResource res = new SystemResource()) {
         Console.WriteLine("A");
      }
      Console.WriteLine("B");
   }
}

class SystemResource : IDisposable {
   public void Dispose() {
      Console.WriteLine("C");
   }
}

Output

A
C
B

Updated on: 20-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements