Click here to Skip to main content
11,412,833 members (77,484 online)
Click here to Skip to main content

Understanding the 'using' statement in C#

, 29 Mar 2004 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Tingz Abraham

United States United States
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

Comments and Discussions

 
GeneralThanks Pin
Alireza_1362 at 28-Feb-15 7:16
memberAlireza_136228-Feb-15 7:16 
QuestionGood explanation Pin
Am Gayathri at 17-Feb-15 23:52
memberAm Gayathri17-Feb-15 23:52 
QuestionThanks! Pin
John Rolando Aristizabal Zuluaga at 12-Feb-15 22:50
memberJohn Rolando Aristizabal Zuluaga12-Feb-15 22:50 
GeneralMy vote of 5 Pin
Afzaal Ahmad Zeeshan at 25-Sep-14 10:11
professionalAfzaal Ahmad Zeeshan25-Sep-14 10:11 
QuestionCan we use Using for objects which does not implement IDisposable Pin
dinesh_ar at 7-Sep-14 22:23
memberdinesh_ar7-Sep-14 22:23 
QuestionAmbiguity Pin
dr.faka at 1-May-14 23:00
memberdr.faka1-May-14 23:00 
AnswerRe: Ambiguity Pin
Tomas Takac at 24-Nov-14 12:25
memberTomas Takac24-Nov-14 12:25 
SuggestionIt is available in vb.net Pin
Jagadeesh Bollabathini at 27-Mar-14 19:28
groupJagadeesh Bollabathini27-Mar-14 19:28 
QuestionWhat happens when i explicitly implement the IDisposable interface? Pin
Rahul VB at 2-Jan-14 21:44
memberRahul VB2-Jan-14 21:44 
GeneralMy vote of 4 Pin
waseem-ricky at 17-Sep-13 22:34
memberwaseem-ricky17-Sep-13 22:34 
GeneralMy vote of 5 Pin
stuy at 19-Sep-12 21:06
memberstuy19-Sep-12 21:06 
GeneralMy vote of 5 Pin
Member 4254057 at 7-Jul-11 19:00
memberMember 42540577-Jul-11 19:00 
GeneralUsing may hide exceptions Pin
Nate Harvey at 1-Jun-11 14:30
memberNate Harvey1-Jun-11 14:30 
GeneralMy vote of 5 Pin
ADELASSI at 30-Apr-11 19:59
memberADELASSI30-Apr-11 19:59 
Generalnice man!!! Pin
Chervonyi at 3-Nov-10 0:04
memberChervonyi3-Nov-10 0:04 
GeneralNice article, 10x Pin
arussev at 12-Aug-10 23:43
memberarussev12-Aug-10 23:43 
GeneralRe: Nice article, 10x Pin
danie_lidstrom at 22-Nov-10 23:18
memberdanie_lidstrom22-Nov-10 23:18 
QuestionWhat happen if the ctor throw an exception ?!? Pin
Fred's Monkey at 6-Aug-09 10:21
memberFred's Monkey6-Aug-09 10:21 
GeneralVB.NET Pin
thejoshwolfe at 9-Dec-08 9:17
memberthejoshwolfe9-Dec-08 9:17 
GeneralRe: VB.NET Pin
Member 7912145 at 7-Oct-11 5:34
memberMember 79121457-Oct-11 5:34 
Questionusing statement Pin
hcheng98 at 19-Nov-08 4:43
memberhcheng9819-Nov-08 4:43 
GeneralError for using statement Pin
BMWABCD at 23-Jul-08 8:23
memberBMWABCD23-Jul-08 8:23 
GeneralRe: Error for using statement Pin
Parameswaranit at 10-Aug-09 0:49
memberParameswaranit10-Aug-09 0:49 
AnswerRe: Error for using statement Pin
pavanCRM at 14-Dec-09 20:37
memberpavanCRM14-Dec-09 20:37 
Generalreturn statement Pin
simonemaynard at 20-Nov-07 10:26
membersimonemaynard20-Nov-07 10:26 
GeneralRe: return statement Pin
Member 4048020 at 16-Jul-08 2:31
memberMember 404802016-Jul-08 2:31 
Question.NET 2.0 Pin
MAC091074 at 12-Sep-07 1:15
memberMAC09107412-Sep-07 1:15 
AnswerRe: .NET 2.0 Pin
blackjack2150 at 13-Jul-08 21:38
memberblackjack215013-Jul-08 21:38 
QuestionGFDL license Pin
Kevin Whitefoot at 10-Jan-06 1:18
memberKevin Whitefoot10-Jan-06 1:18 
Generalusing statement Pin
bbmurali_2000@yahoo.com at 16-May-05 20:40
memberbbmurali_2000@yahoo.com16-May-05 20:40 
GeneralThere is no Catch! Pin
Ed K at 30-Mar-04 5:23
memberEd K30-Mar-04 5:23 
GeneralRe: There is no Catch! Pin
Ian Griffiths at 31-Mar-04 23:40
memberIan Griffiths31-Mar-04 23:40 
Generalgreat article Pin
martininick at 30-Mar-04 4:06
membermartininick30-Mar-04 4:06 
Generalsealed Pin
Jonathan de Halleux at 30-Mar-04 3:35
memberJonathan de Halleux30-Mar-04 3:35 
GeneralRe: sealed Pin
Maximilian Hänel at 30-Mar-04 5:36
memberMaximilian Hänel30-Mar-04 5:36 

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 | Terms of Use | Mobile
Web01 | 2.8.150427.1 | Last Updated 30 Mar 2004
Article Copyright 2004 by Tingz Abraham
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid