Click here to Skip to main content
Licence 
First Posted 29 Mar 2004
Views 156,156
Bookmarked 55 times

Understanding the 'using' statement in C#

By | 29 Mar 2004 | Article
Understanding the 'using' statement in C#

Introduction

This article is an introduction to the using statement in c# and also provides some insight into the actual implementation of the statement.

The Code

When you are using an object that encapsulates any resource, you have to make sure that when you are done with the object, the object's Dispose method is called. This can be done more easily using the using statement in C#. The using statement simplifies the code that you have to write to create and then finally clean up the object. The using statement obtains the resource specified, executes the statements and finally calls the Dispose method of the object to clean up the object. The following piece of code illustrates its use.

using (TextWriter w = File.CreateText("log.txt"))
{
    w.WriteLine("This is line one");
}

Now that's cool. But before we can start using this code, let us try to understand what happens behind the screen. Lets have a look at the IL code for the above code section.

.locals init ([0] class [mscorlib]System.IO.TextWriter w)
  IL_0000:  ldstr      "log.txt"
  IL_0005:  call       class [mscorlib]System.IO.StreamWriter 
      [mscorlib]System.IO.File::CreateText(string)
  IL_000a:  stloc.0
 
 .try
  {
    IL_000b:  ldloc.0
    IL_000c:  ldstr      "This is line one"
    IL_0011:  callvirt   instance void [mscorlib]
      System.IO.TextWriter::WriteLine(string)
    IL_0016:  leave.s    IL_0022
  }  // end .try
  finally
  {
    IL_0018:  ldloc.0
    IL_0019:  brfalse.s  IL_0021
    IL_001b:  ldloc.0
    IL_001c:  callvirt   instance void [mscorlib]
      System.IDisposable::Dispose()
    IL_0021:  endfinally
  }  // end handler

Hmmmm.... Well doesn't look like this is my code. That's because I see a try and a finally in the IL code (something that I haven't implemented). Wait a minute. IT IS MY CODE....

Waaaaaah... Somebody changed my code...

Well the truth is, somebody did change your code. The CLR. The CLR converts your code into MSIL. And the using statement gets translated into a try and finally block. This is how the using statement is represented in IL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause. For example the following lines of code using the using statement,

using (MyResource myRes = new MyResource())
{
    myRes.DoSomething();

}

gets translated to,

    
MyResource myRes= new MyResource();
try
{
    myRes.DoSomething();
}
finally
{
    // Check for a null resource.
    if (myRes!= null)
        // Call the object's Dispose method.
        ((IDisposable)myRes).Dispose();
}

Hmmm... That explains it.

The above code that uses the using statement corresponds to one of the two possible expansions. When MyResource is a value type, the expansion in the finally block will be

finally
{
((IDisposable)myRes).Dispose();
}

If MyResource is of reference type, the expansion becomes

finally
{
if(myRes != null)
((IDisposable)myRes).Dispose();
}

This way, if a null resource is acquired, then no call will be made to Dispose, thus avoiding any exception that occurs.
Well, that explains everything.

Using 'using'

A typical scenario where we could use the using statement is :

string connString = "Data Source=localhost;Integrated " + 
  "Security=SSPI;Initial Catalog=Northwind;";

using (SqlConnection conn = new SqlConnection(connString))
{
  SqlCommand cmd = conn.CreateCommand();
  cmd.CommandText = "SELECT ID, Name FROM Customers";
  
  conn.Open();

  using (SqlDataReader dr = cmd.ExecuteReader())
  {
    while (dr.Read())
      Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
  }
}

Note

The using statement is only useful for objects with a lifetime that does not extend beyond the method in which the objects are constructed. Remember that the objects you instantiate must implement the System.IDisposable interface.

There is no equivalent for the using statement in vb.net. You have to use the try finally block.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Tingz Abraham



United States United States

Member

When Tingz Abraham was old enough to realize that computers were going to invade the world, he decided to pursue a career that would keep him close to computers. That landed him a job as an IT Solutions Consultant in Seattle, USA where he currently works. He believes he can program in many languages, including English. Ctrl+C and Ctrl+V are his favorite keys on the keyboard.
 
After he found he sucked real bad at playing the violin, he just stuck to the guitar and piano. He has a ravishing need for speed and takes a fancy to anything with wheels, including his black Mustang which he's aptly named 'Tingzmobile'.
 
At work you can constantly hear him say - "Oh! The things I learn after I know it all!" He keeps himself very busy, and in his spare time he keeps wondering why '24 hours a day is just not enough'.
 
He exists at www.Tingzabraham.com

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

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 PinmemberMember 425405718:00 7 Jul '11  
GeneralUsing may hide exceptions PinmemberNate Harvey13:30 1 Jun '11  
GeneralMy vote of 5 PinmemberADELASSI18:59 30 Apr '11  
Generalnice man!!! PinmemberChervonyi23:04 2 Nov '10  
GeneralNice article, 10x Pinmemberarussev22:43 12 Aug '10  
GeneralRe: Nice article, 10x Pinmemberdanie_lidstrom22:18 22 Nov '10  
QuestionWhat happen if the ctor throw an exception ?!? PinmemberFred's Monkey9:21 6 Aug '09  
GeneralVB.NET Pinmemberthejoshwolfe8:17 9 Dec '08  
GeneralRe: VB.NET PinmemberMember 79121454:34 7 Oct '11  
Questionusing statement Pinmemberhcheng983:43 19 Nov '08  
GeneralError for using statement PinmemberBMWABCD7:23 23 Jul '08  
GeneralRe: Error for using statement PinmemberParameswaranit23:49 9 Aug '09  
AnswerRe: Error for using statement PinmemberpavanCRM19:37 14 Dec '09  
Generalreturn statement Pinmembersimonemaynard9:26 20 Nov '07  
GeneralRe: return statement PinmemberMember 40480201:31 16 Jul '08  
Question.NET 2.0 PinmemberMAC0910740:15 12 Sep '07  
AnswerRe: .NET 2.0 Pinmemberblackjack215020:38 13 Jul '08  
QuestionGFDL license PinmemberKevin Whitefoot0:18 10 Jan '06  
Generalusing statement Pinmemberbbmurali_2000@yahoo.com19:40 16 May '05  
Hi,
 
Your sample programs on using statement are very useful to me.
 
Thanks a lot.
 
Sigh | :sigh: of relief
GeneralThere is no Catch! PinmemberEd K4:23 30 Mar '04  
GeneralRe: There is no Catch! PinmemberIan Griffiths22:40 31 Mar '04  
Generalgreat article Pinmembermartininick3:06 30 Mar '04  
Generalsealed PinmemberJonathan de Halleux2:35 30 Mar '04  
GeneralRe: sealed PinmemberMaximilian Hänel4:36 30 Mar '04  

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.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120528.1 | Last Updated 30 Mar 2004
Article Copyright 2004 by Tingz Abraham
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid