Click here to Skip to main content
15,878,970 members
Articles / Programming Languages / C#

The using Keyword and IDisposable

Rate me:
Please Sign up or sign in to vote.
2.55/5 (17 votes)
8 May 2009CPOL2 min read 52.5K   11   25
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():

C#
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:

C#
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:

C#
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)


Written By
Software Developer
Israel Israel

Comments and Discussions

 
Generalrequest to visitors Pin
Siddhartha S.20-Apr-10 23:39
Siddhartha S.20-Apr-10 23:39 
GeneralRe: request to visitors Pin
PIEBALDconsult21-Apr-10 3:14
mvePIEBALDconsult21-Apr-10 3:14 
GeneralRe: request to visitors Pin
Siddhartha S.21-Apr-10 3:44
Siddhartha S.21-Apr-10 3:44 
GeneralRe: request to visitors Pin
PIEBALDconsult21-Apr-10 8:01
mvePIEBALDconsult21-Apr-10 8:01 
Question[My vote of 1] What, another article with the same information? Pin
Sergey Alexandrovich Kryukov16-Nov-09 11:43
mvaSergey Alexandrovich Kryukov16-Nov-09 11:43 
AnswerRe: [My vote of 1] What, another article with the same information? Pin
Omer .NETz17-Nov-09 6:26
Omer .NETz17-Nov-09 6:26 
General[My vote of 2] More detail Pin
Donsw1-Jun-09 17:00
Donsw1-Jun-09 17:00 
GeneralMy vote of 1 Pin
YoniP20-May-09 23:10
YoniP20-May-09 23:10 
GeneralMy vote of 1 Pin
Izzet Kerem Kusmezer8-May-09 4:22
Izzet Kerem Kusmezer8-May-09 4:22 
GeneralMy vote of 1 Pin
M.R.P4-May-09 18:05
professionalM.R.P4-May-09 18:05 
GeneralA little more detail please..... Pin
Glen Harvy4-May-09 12:04
Glen Harvy4-May-09 12:04 
GeneralRe: A little more detail please..... Pin
PIEBALDconsult8-May-09 4:37
mvePIEBALDconsult8-May-09 4:37 
GeneralRe: A little more detail please..... Pin
Glen Harvy8-May-09 12:24
Glen Harvy8-May-09 12:24 
GeneralRe: A little more detail please..... Pin
PIEBALDconsult8-May-09 12:50
mvePIEBALDconsult8-May-09 12:50 
GeneralRe: A little more detail please..... Pin
Siddhartha S.20-Apr-10 23:22
Siddhartha S.20-Apr-10 23:22 
GeneralRe: A little more detail please..... Pin
PIEBALDconsult21-Apr-10 3:18
mvePIEBALDconsult21-Apr-10 3:18 
GeneralRe: A little more detail please..... Pin
Siddhartha S.21-Apr-10 3:40
Siddhartha S.21-Apr-10 3:40 
GeneralRe: A little more detail please..... Pin
PIEBALDconsult21-Apr-10 7:57
mvePIEBALDconsult21-Apr-10 7:57 
AnswerRe: A little more detail please..... Pin
Omer .NETz8-May-09 5:17
Omer .NETz8-May-09 5:17 
GeneralRe: A little more detail please..... Pin
Glen Harvy8-May-09 12:24
Glen Harvy8-May-09 12:24 
GeneralNeedless Pin
PIEBALDconsult29-Apr-09 13:53
mvePIEBALDconsult29-Apr-09 13:53 
GeneralRe: Needless Pin
Omer .NETz29-Apr-09 20:25
Omer .NETz29-Apr-09 20:25 
AnswerRe: Needless Pin
xlg4-May-09 21:51
xlg4-May-09 21:51 
GeneralRe: Needless Pin
YoniP20-May-09 23:12
YoniP20-May-09 23:12 
GeneralRe: Needless Pin
Siddhartha S.20-Apr-10 23:25
Siddhartha S.20-Apr-10 23:25 

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

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