using
is a C# keyword that acts as a syntactic-sugar for dealing with IDisposible objects. As per MSDN
using block Defines a scope, outside of which an object or objects will be disposed.
The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object’s resources.
Surprisingly even MSDN does not clarify how does this happen under the hood. It only says the object has to implement IDisposable interface that provides Dispose method on the object implementing the interface. So to dispose the object it will need to call the Dispose method on the object which will cleanup and release the resources used by the object.
Take a look at this example..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlogSamples
{
class Program
{
static void Main(string[] args)
{
//Assume that Car is IDisposible.
using (Car myCar = new Car(1))
{
myCar.Run();
}
}
}
}
Compiler converts to code to look like this..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlogSamples
{
class Program
{
static void Main(string[] args)
{
//Declare myCar object with FullName of the type as seen in IL.
BlogSamples.Car myCar;
//Instantiate the object by calling the constructor, matching the flow of IL.
myCar = new Car(1);
try
{
myCar.Run();
}
finally
{
if(myCar != null)
myCar.Dispose();
}
}
}
}
To understand how exactly the using block works under the hood, I recommend you read this blog-post.
http://www.ruchitsurati.net/index.php/2010/07/28/understanding-%E2%80%98using%E2%80%99-block-in-c/