In Focus

The "Using" Statement In C#

C# using statement makes sure that the allocated objects within the using statement is disposed once the using block code is executed.

C# using

The .Net Framework provides resource management for managed objects through the garbage collector - You do not have to explicitly allocate and release memory for managed objects. Clean-up operations for any unmanaged resources should be performed in the destructor in C#.
 
To allow the programmer to explicitly perform these clean-up activities, objects can provide a Dispose method that can be invoked when the object is no longer needed. The using statement in C# defines a boundary for the object outside of which, the object is automatically destroyed. The using statement is exited when the end of the "using" statement block or the execution exits the "using" statement block indirectly, for example - an exception is thrown.
 
The "using" statement allows you to specify multiple resources in a single statement. The object could also be created outside the "using" statement. The objects specified within the using block must implement the IDisposable interface. The framework invokes the Dispose method of objects specified within the "using" statement when the block is exited.

Note

The MyManagedClass class is not a part of the .NET Framework and is only used in the example for demonstration. The MyManagedClass class needs to be released explicitly and implements the IDisposable interface.
 
Example 1
  1. .......  
  2. using (MyManagedClass mnObj = new MyManagedClass())  
  3. {  
  4. ......  
  5. mnObj.Use(); //use the mnObj object  
  6. ......  
  7. //The compiler will dispose the mnObj object now  
  8. ......  

Example 2

  1. ......  
  2. MyManagedClass mnObj =new MyManagedClass()  
  3. using (mnObj)  
  4. {  
  5. ......  
  6. mnObj.Use();//use the mnObj object  
  7. ......  
  8. }//The mnObj object will disposed now  
  9. ......   

Note that the using Directive in C# is different from the using statement. The "using" Directive is used to provide an alias for a namespace.

NOTE


This article is purely for demonstration. This article should not be construed as a best practices white paper. This article is entirely original unless specified. Any resemblance to other material is an unintentional coincidence.
 
Next Reading
 
The using in .NET and C# has more usage. Here is a complete article: