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

The using Keyword and IDisposable

, 8 May 2009
Rate this:
Please Sign up or sign in to vote.
Accessing IDisposable objects in a bounded scope with the using keyword

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

Comments and Discussions

 
Generalrequest to visitors Pinmemberbabai2820-Apr-10 23:39 
GeneralRe: request to visitors PinmvpPIEBALDconsult21-Apr-10 3:14 
GeneralRe: request to visitors Pinmemberbabai2821-Apr-10 3:44 
GeneralRe: request to visitors PinmvpPIEBALDconsult21-Apr-10 8:01 
Question[My vote of 1] What, another article with the same information? PinmemberSAKryukov16-Nov-09 11:43 
AnswerRe: [My vote of 1] What, another article with the same information? PinmemberOmer .NETz17-Nov-09 6:26 
General[My vote of 2] More detail PinmemberDonsw1-Jun-09 17:00 
GeneralMy vote of 1 PinmemberYoniP20-May-09 23:10 
GeneralMy vote of 1 PinmemberIzzet Kerem Kusmezer8-May-09 4:22 
GeneralMy vote of 1 PinmemberM.R.P4-May-09 18:05 
GeneralA little more detail please..... PinmemberGlen Harvy4-May-09 12:04 
GeneralRe: A little more detail please..... PinmemberPIEBALDconsult8-May-09 4:37 
GeneralRe: A little more detail please..... PinmemberGlen Harvy8-May-09 12:24 
GeneralRe: A little more detail please..... PinmemberPIEBALDconsult8-May-09 12:50 
GeneralRe: A little more detail please..... Pinmemberbabai2820-Apr-10 23:22 
GeneralRe: A little more detail please..... PinmvpPIEBALDconsult21-Apr-10 3:18 
GeneralRe: A little more detail please..... Pinmemberbabai2821-Apr-10 3:40 
GeneralRe: A little more detail please..... PinmvpPIEBALDconsult21-Apr-10 7:57 
I didn't say "must". However, I don't see any reason not to have any particular class not be disposable simply because it doesn't use unmanaged resources.
AnswerRe: A little more detail please..... PinmemberOmer Hanetz8-May-09 5:17 
GeneralRe: A little more detail please..... PinmemberGlen Harvy8-May-09 12:24 
GeneralNeedless PinmemberPIEBALDconsult29-Apr-09 13:53 
GeneralRe: Needless PinmemberOmer Hanetz29-Apr-09 20:25 
AnswerRe: Needless Pinmemberxlg4-May-09 21:51 
GeneralRe: Needless PinmemberYoniP20-May-09 23:12 
GeneralRe: Needless Pinmemberbabai2820-Apr-10 23:25 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 8 May 2009
Article Copyright 2009 by Omer .NETz
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid