Tuesday 20 September 2011

using keyword

The using Keyword and IDisposable
The using keyword is well known to C# developers. Its main purpose, the using directive, is to create a shortcut to namespaces used in the code, but it's not the only purpose. using can also be used to access an object in a bounded scope if this object's type implements the IDisposable interface, which means it contains a public Dispose() method.
The main advantage of the using statement is resources releasing management. Usually, the .NET Framework Garbage Collector controls resources releasing. With the using statement, we can take the control:
  • Decide when resources should be released
  • Implement the Dispose() method, and then decide exactly which resources will be released
Using the Code
Assume we have a class called MyClass. This class implements the IDisposable interface, which means it contains a public Dispose() method. It also has another public method – DoSomething():
Collapse
class MyClass : IDisposable
{
    public void DoSomething()
    {
        // Something...
    }
    public void Dispose()
    {
        // Disposing Class...
    }
}
With the using statement, we can create an instance of MyClass in a bounded scope:
static void Main(string[] args)
{
    using (MyClass myClazz = new MyClass())
    {
        myClazz.DoSomething();
    }
}
Inside the using statement, we can use myClazz as a regular instance of MyClass – in this case, call its public method. Outside the using statement, myClazz doesn't exist.
What happens behind the scenes? Actually, it's very simple. The C# compiler will translate the above using statement at compile time into something like this:
static void Main(string[] args)
{
    {
        MyClass myClazz = new MyClass();
        try
        {
            myClazz.DoSomething();
        }
        finally
        {
            IDisposable dis = myClazz as IDisposable;
            if (dis != null)
            {
                dis.Dispose();
            }
        }
    }
}
The MyClass instance is used inside a try block. At the end of the use, the finally block is called. Here, we dispose the instance, by calling the Dispose() method of MyClass.

No comments:

Post a Comment