Click here to Skip to main content
15,437,583 members
Articles / Programming Languages / C#
Posted 29 Mar 2004


102 bookmarked

Understanding the 'using' statement in C#

Rate me:
Please Sign up or sign in to vote.
4.71/5 (106 votes)
29 Mar 2004CPOL2 min read
Understanding the 'using' statement in C#


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 
  IL_000a:  stloc.0
    IL_000b:  ldloc.0
    IL_000c:  ldstr      "This is line one"
    IL_0011:  callvirt   instance void [mscorlib]
    IL_0016:  leave.s    IL_0022
  }  // end .try
    IL_0018:  ldloc.0
    IL_0019:  brfalse.s  IL_0021
    IL_001b:  ldloc.0
    IL_001c:  callvirt   instance void [mscorlib]
    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())


gets translated to,

MyResource myRes= new MyResource();
    // Check for a null resource.
    if (myRes!= null)
        // Call the object's Dispose method.

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


If MyResource is of reference type, the expansion becomes

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

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";

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


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 You have to use the try finally block.


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

Written By
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

QuestionQuestion: Using Statement Pin
Member 139023187-Jul-18 4:57
MemberMember 139023187-Jul-18 4:57 
SuggestionGreat article Pin
Rizwan Gazi26-Sep-16 21:47
MemberRizwan Gazi26-Sep-16 21:47 
GeneralMy vote of 4 Pin
Umesh AP11-May-16 19:24
MemberUmesh AP11-May-16 19:24 
PraiseGreat Article Pin
vipan.net10-Jan-16 18:21
professionalvipan.net10-Jan-16 18:21 
QuestionWhat if reference to object passed outside of the class? Pin
Manjit Dosanjh10-Jan-16 9:56
MemberManjit Dosanjh10-Jan-16 9:56 
GeneralRe: What if reference to object passed outside of the class? Pin
PIEBALDconsult10-Jan-16 10:10
professionalPIEBALDconsult10-Jan-16 10:10 
PraiseThanks Pin
taymyinl4-Jan-16 20:54
Membertaymyinl4-Jan-16 20:54 
GeneralGreat explanation! Pin
Member 111723931-Sep-15 19:15
professionalMember 111723931-Sep-15 19:15 
GeneralThanks Pin
Alireza_136228-Feb-15 6:16
MemberAlireza_136228-Feb-15 6:16 
QuestionGood explanation Pin
Am Gayathri17-Feb-15 22:52
MemberAm Gayathri17-Feb-15 22:52 
QuestionThanks! Pin
John Rolando Aristizabal Zuluaga12-Feb-15 21:50
MemberJohn Rolando Aristizabal Zuluaga12-Feb-15 21:50 
GeneralMy vote of 5 Pin
Afzaal Ahmad Zeeshan25-Sep-14 9:11
mveAfzaal Ahmad Zeeshan25-Sep-14 9:11 
QuestionCan we use Using for objects which does not implement IDisposable Pin
dinesh_ar7-Sep-14 21:23
Memberdinesh_ar7-Sep-14 21:23 
QuestionAmbiguity Pin
drfpo1-May-14 22:00
Memberdrfpo1-May-14 22:00 
AnswerRe: Ambiguity Pin
Tomas Takac24-Nov-14 11:25
MemberTomas Takac24-Nov-14 11:25 
SuggestionIt is available in Pin
Jagadeesh Bollabathini27-Mar-14 18:28
MemberJagadeesh Bollabathini27-Mar-14 18:28 
QuestionWhat happens when i explicitly implement the IDisposable interface? Pin
Rahul VB2-Jan-14 20:44
professionalRahul VB2-Jan-14 20:44 
GeneralMy vote of 4 Pin
Waseem-Malik17-Sep-13 21:34
professionalWaseem-Malik17-Sep-13 21:34 
GeneralMy vote of 5 Pin
stuy19-Sep-12 20:06
Memberstuy19-Sep-12 20:06 
GeneralMy vote of 5 Pin
Member 42540577-Jul-11 18:00
MemberMember 42540577-Jul-11 18:00 
GeneralUsing may hide exceptions Pin
Nate Harvey1-Jun-11 13:30
MemberNate Harvey1-Jun-11 13:30 
GeneralMy vote of 5 Pin
ADELASSI30-Apr-11 18:59
MemberADELASSI30-Apr-11 18:59 
Generalnice man!!! Pin
Chervonyi2-Nov-10 23:04
MemberChervonyi2-Nov-10 23:04 
GeneralNice article, 10x Pin
arussev12-Aug-10 22:43
Memberarussev12-Aug-10 22:43 
GeneralRe: Nice article, 10x Pin
danie_lidstrom22-Nov-10 22:18
Memberdanie_lidstrom22-Nov-10 22:18 

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.