Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Article

The "using" Keyword in C#

Rate me:
Please Sign up or sign in to vote.
4.52/5 (79 votes)
10 Jan 2007CPOL3 min read 306.8K   51   73
A look at the C# "using" keyword. What happens behind the scenes.

Introduction

I was at work today, and someone asked me what happens when you use the using keyword in C#. Most people will tell you that it is something you use that will clean up any unmanaged resources for the specified object, which is not incorrect. But what actually happens at the IL level? How does it "clean up" unmanaged resources? I had my assumptions, but I really didn't know. So, I set out to find out for myself.

Tests

I decided I was going to run through a couple of tests:

Test #1

I wanted to see what the generated MSIL code looks like when I use the using keyword. So, I wrote some very simple sample code in C#, compiled it, then I decompiled it using ildasm to see the MSIL code.

Test #2

I wanted to see if I could write code without using the using keyword that would generate the exact same MSIL code. This process was a little more trial and error, but was fairly easy.

Test #1

Here is my sample code:

C#
[STAThread]
private static void Main(string[] args)
{
      using (Bitmap bitmap1 = new Bitmap(100, 100))
      {
            Console.WriteLine("Width: {0}, Height: {1}", bitmap1.Width, bitmap1.Height);
      }
      Console.ReadLine();
}

As you can see... nothing special in the code. Create a new Bitmap inside a using statement, write some output to the console, wait for user input, then exit.

What does this look like when we build the app, then decompile it into MSIL? Check it out:

MSIL
.method private hidebysig static void Main(string[] args) cil managed
{
      .custom instance void [mscorlib]System.STAThreadAttribute::.ctor()
      .entrypoint
      .maxstack 4
      .locals init (
            [0] [System.Drawing]System.Drawing.Bitmap bitmap1)
      L_0000: ldc.i4.s 100
      L_0002: ldc.i4.s 100
      L_0004: newobj instance void 
	[System.Drawing]System.Drawing.Bitmap::.ctor(int32, int32)
      L_0009: stloc.0 
      L_000a: ldstr "Width: {0}, Height: {1}"
      L_000f: ldloc.0 
      L_0010: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Width()
      L_0015: box int32
      L_001a: ldloc.0 
      L_001b: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Height()
      L_0020: box int32
      L_0025: call void [mscorlib]System.Console::WriteLine(string, object, object)
      L_002a: leave.s L_0036
      L_002c: ldloc.0 
      L_002d: brfalse.s L_0035
      L_002f: ldloc.0 
      L_0030: callvirt instance void [mscorlib]System.IDisposable::Dispose()
      L_0035: endfinally 
      L_0036: call string [mscorlib]System.Console::ReadLine()
      L_003b: pop 
      L_003c: ret 
      .try L_000a to L_002c finally handler L_002c to L_0036
}

Test #1 Results

So the results from test #1 are interesting. The using keyword is basically a try - finally block, without a catch , where IDisposable.Dispose() is called in the finally . One interesting thing to note is that the Bitmap constructor is called before the try block begins. This tells me that if, in the Bitmap constructor, an unmanaged resource is allocated, but not freed, then the constructor throws an exception, the unmanaged resource will not get freed by a call to the IDisposable.Dispose(). This also assumes that the IDisposable is implemented properly. Therefore the using keyword is useless if the IDisposable is not implemented properly. The constructor should clean up resources if it fails, and the Dispose() method should clean up all unmanaged resources. Chances are good that Microsoft has implemented IDisposable correctly in their classes, so watch out for this if you are implementing your own IDisposable.

Test #2

Based on the MSIL code that resulted from Test #1, I decided to write the same code using try - finally blocks. This is what I came up with:

C#
[STAThread]
private static void Main(string[] args)
{
      Bitmap bitmap1 = new Bitmap(100, 100);
      try
      {
            Console.WriteLine("Width: {0}, Height: {1}", bitmap1.Width, bitmap1.Height);
      }
      finally
      {
            if (bitmap1 != null)
            {
                  bitmap1.Dispose();
            }
      }
      Console.ReadLine();
}

And this is what it looked like in MSIL:

MSIL
.method private hidebysig static void Main(string[] args) cil managed
{
      .custom instance void [mscorlib]System.STAThreadAttribute::.ctor()
      .entrypoint
      .maxstack 4
      .locals init (
            [0] [System.Drawing]System.Drawing.Bitmap bitmap1)
      L_0000: ldc.i4.s 100
      L_0002: ldc.i4.s 100
      L_0004: newobj instance void 
	[System.Drawing]System.Drawing.Bitmap::.ctor(int32, int32)
      L_0009: stloc.0 
      L_000a: ldstr "Width: {0}, Height: {1}"
      L_000f: ldloc.0 
      L_0010: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Width()
      L_0015: box int32
      L_001a: ldloc.0 
      L_001b: callvirt instance int32 [System.Drawing]System.Drawing.Image::get_Height()
      L_0020: box int32
      L_0025: call void [mscorlib]System.Console::WriteLine(string, object, object)
      L_002a: leave.s L_0036
      L_002c: ldloc.0 
      L_002d: brfalse.s L_0035
      L_002f: ldloc.0 
      L_0030: callvirt instance void [System.Drawing]System.Drawing.Image::Dispose()
      L_0035: endfinally 
      L_0036: call string [mscorlib]System.Console::ReadLine()
      L_003b: pop 
      L_003c: ret 
      .try L_000a to L_002c finally handler L_002c to L_0036
}

Test #2 Results

It is almost exactly like the MSIL generated from the using keyword, except this calls Image.Dispose() rather than IDisposable.Dispose(), but the effect is the same. Just for fun, I regenerated C# code using Lutz Roeder's .NET Reflector, which is an invaluable tool, and here is the result:

C#
[STAThread]
private static void Main(string[] args)
{
      using (Bitmap bitmap1 = new Bitmap(100, 100))
      {
            Console.WriteLine("Width: {0}, Height: {1}", bitmap1.Width, bitmap1.Height);
      }
      Console.ReadLine();
}

This looks exactly like our original code!!!

Conclusion

This was really a fun experiment that revealed a lot about the way .NET works behind the scenes. I hope you guys enjoy this as much as I did.

History

  • 10th January, 2007: Initial post

License

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


Written By
Architect People Media
United States United States
My name is Peter Femiani and I am a graduate of Arizona State University with a B.S. in Economics. I have been writing code since I was about 14.

Comments and Discussions

 
GeneralRe: Uh.. Pin
ttobler15-Jan-07 9:24
ttobler15-Jan-07 9:24 
GeneralRe: Uh.. Pin
Scott Dorman15-Jan-07 17:36
professionalScott Dorman15-Jan-07 17:36 
GeneralRe: Uh.. Pin
Peter Ritchie15-Jan-07 5:21
Peter Ritchie15-Jan-07 5:21 
QuestionC# Memory Management - The "using" keyword Pin
Fabio Galante Mans11-Jan-07 2:26
Fabio Galante Mans11-Jan-07 2:26 
AnswerRe: C# Memory Management - The "using" keyword Pin
ADLER111-Jan-07 10:16
ADLER111-Jan-07 10:16 
AnswerRe: C# Memory Management - The "using" keyword Pin
Scott Dorman11-Jan-07 13:56
professionalScott Dorman11-Jan-07 13:56 
GeneralRe: C# Memory Management - The "using" keyword Pin
ADLER111-Jan-07 22:15
ADLER111-Jan-07 22:15 
GeneralRe: C# Memory Management - The "using" keyword Pin
Scott Dorman12-Jan-07 13:06
professionalScott Dorman12-Jan-07 13:06 
Yes, the answers are very close. There are several classes where Close and Dispose can be used interchangeable, most notably SqlConnection and any of the Stream derived classes. It is a fairly common extension to the IDisposable pattern. I only addressed SqlConnection in my other response as the original example focused on it.

-----------------------------
In just two days, tomorrow will be yesterday.

GeneralGreat! Pin
Paul Brower11-Jan-07 1:39
Paul Brower11-Jan-07 1:39 
GeneralYou have my 5! Pin
Leonardo Pessoa11-Jan-07 0:05
Leonardo Pessoa11-Jan-07 0:05 
GeneralNot quite the same Pin
Cliff Stanford11-Jan-07 0:04
Cliff Stanford11-Jan-07 0:04 
AnswerRe: Not quite the same Pin
pfemiani11-Jan-07 0:50
pfemiani11-Jan-07 0:50 
GeneralRe: Not quite the same Pin
Cliff Stanford11-Jan-07 5:57
Cliff Stanford11-Jan-07 5:57 
GeneralThanks! Pin
wally66610-Jan-07 21:20
wally66610-Jan-07 21:20 
GeneralInteresting read ... Pin
Bryan Ray10-Jan-07 20:12
Bryan Ray10-Jan-07 20:12 
GeneralExecption in Constructor Pin
Steve Hansen10-Jan-07 19:55
Steve Hansen10-Jan-07 19:55 
AnswerRe: Execption in Constructor Pin
pfemiani10-Jan-07 21:01
pfemiani10-Jan-07 21:01 
GeneralRe: Execption in Constructor Pin
Scott Dorman11-Jan-07 13:59
professionalScott Dorman11-Jan-07 13:59 
GeneralEverybody should be using using... Pin
Axel Rietschin10-Jan-07 18:37
professionalAxel Rietschin10-Jan-07 18:37 

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.