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

CsharpProgrammingServer Side Programming

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
raja
Published on 10-Aug-2018 10:36:07
Advertisements