Click here to Skip to main content
Click here to Skip to main content

The using Keyword and IDisposable

By , 8 May 2009
 

Introduction

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.

Background

There are two types of object resources: managed and unmanaged:

  • Managed Resource - A .NET Framework object, built only from .NET Framework code, without any external references (For example: string, integer). The Garbage Collector handles managed resources, and releases them when they are not in use.
  • Unmanaged Resource - An object inside or outside the .NET Framework, which uses external code (For example: file handles, streams, DB connections). The Garbage Collector can't handle unmanaged resources, so we need to release them manually.

The Dispose() method is used to manually release all the resources of an object. It is useless for objects that contain only managed resources, which are already automatically released by the Garbage Collector.

On the other hand, it is useful for objects that contain unmanaged resources:

  • Free resources held by an object.
  • Prepare object for reuse.

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():

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.

Notice the extra braces around the code. They are used to create the bounded scope for the object.

Points of Interest

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

This way, the only resources we keep will be those we really need.

Notice

This article, and more about programming can be found in my blog here.

History

  • 08.05.09 - Third version - Added background information about Dispose(), managed and umnanaged resources. Thanks Glen Harvy, xlg for your comments
  • 01.05.09 - Second version - thanks PIEBALDconsult for your comment
  • 29.04.09 - Original version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Omer .NETz
Software Developer
Israel Israel
Member

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalrequest to visitorsmemberbabai2820 Apr '10 - 23:39 
GeneralRe: request to visitorsmvpPIEBALDconsult21 Apr '10 - 3:14 
GeneralRe: request to visitorsmemberbabai2821 Apr '10 - 3:44 
GeneralRe: request to visitorsmvpPIEBALDconsult21 Apr '10 - 8:01 
Question[My vote of 1] What, another article with the same information?memberSAKryukov16 Nov '09 - 11:43 
AnswerRe: [My vote of 1] What, another article with the same information?memberOmer .NETz17 Nov '09 - 6:26 
General[My vote of 2] More detailmemberDonsw1 Jun '09 - 17:00 
GeneralMy vote of 1memberYoniP20 May '09 - 23:10 
GeneralMy vote of 1memberIzzet Kerem Kusmezer8 May '09 - 4:22 
GeneralMy vote of 1memberM.R.P4 May '09 - 18:05 
GeneralA little more detail please.....memberGlen Harvy4 May '09 - 12:04 
GeneralRe: A little more detail please.....memberPIEBALDconsult8 May '09 - 4:37 
GeneralRe: A little more detail please.....memberGlen Harvy8 May '09 - 12:24 
GeneralRe: A little more detail please.....memberPIEBALDconsult8 May '09 - 12:50 
GeneralRe: A little more detail please.....memberbabai2820 Apr '10 - 23:22 
GeneralRe: A little more detail please.....mvpPIEBALDconsult21 Apr '10 - 3:18 
GeneralRe: A little more detail please.....memberbabai2821 Apr '10 - 3:40 
GeneralRe: A little more detail please.....mvpPIEBALDconsult21 Apr '10 - 7:57 
AnswerRe: A little more detail please.....memberOmer Hanetz8 May '09 - 5:17 
GeneralRe: A little more detail please.....memberGlen Harvy8 May '09 - 12:24 
GeneralNeedlessmemberPIEBALDconsult29 Apr '09 - 13:53 
GeneralRe: NeedlessmemberOmer Hanetz29 Apr '09 - 20:25 
AnswerRe: Needlessmemberxlg4 May '09 - 21:51 
GeneralRe: NeedlessmemberYoniP20 May '09 - 23:12 
GeneralRe: Needlessmemberbabai2820 Apr '10 - 23:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 8 May 2009
Article Copyright 2009 by Omer .NETz
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid