Home » Advanced CSharp » Dispose with Using

Dispose with Using

misc_vol3_087 I’m sure that many of you already know that many of the objects in the .NET framework need to be disposed.  The most common of these are the windows objects and the stream objects.

Of course the trick in using dispose is in calling it at the right time.  If your code throws an exception, you need to make sure that dispose still gets called on that object.

The standard code for ensuring that dispose gets called looks like:

System.IO.FileStream fs =
    new System.IO.FileStream("c:\\file.txt",
        System.IO.FileMode.Open);
try
{
    // do something with fs here
}
finally
{
    fs.Dispose();
}

Which can get pretty cumbersome if you are dealing with multiple objects that need to be disposed.

This is where the usings statement comes in handy.  By using(fs) we avoid having to write out the finally block:

System.IO.FileStream fs =
    new System.IO.FileStream("c:\\file.txt",
        System.IO.FileMode.Open);
using(fs)
{
    // do something with fs here
}

When the code compiles to intermediate language, it translates the using statement into the try/finally syntax I showed you above.

You can also embed the constructor line in your using statement:

using (System.IO.FileStream fs =
    new System.IO.FileStream("c:\\file.txt",
        System.IO.FileMode.Open))
{
    // do something here
}

And you can combine multiple statements in your using block as long as the types match so that if you were doing a file copy operation your code might look something like this:

using (System.IO.FileStream fs =
    new System.IO.FileStream("c:\\file.txt",
        System.IO.FileMode.Open),
        fs2 =
    new System.IO.FileStream("c:\\file2.txt",
        System.IO.FileMode.CreateNew))
{
    // do something here
}

Notice in the code above that we did not have to declare fs2 as a FileStream because it was declared as such when we declared fs.

If you have objects of multiple types being used, you will need to use multiple using statements.  Fortunately, we don’t run into this situation frequently so the syntax cleans up our code nicely most of the time.

 

Other post in Advanced CSharp

Related Post

  • Dispose, Finalize and SuppressFinalizeDispose, Finalize and SuppressFinalize I got the following question recently. What is the difference between Dispose and SupressFinalize in garbage collection?” The problem with this question is it assumes Dispose and […]
  • using – There’s more there than you are usingusing – There’s more there than you are using If you've spent more than a day programming in CSharp, you have already discovered the need for the using directive: using System; using System.Collections.Generic; using […]
  • CSharp Numeric OverflowsCSharp Numeric Overflows Did you know that when you are dealing with numbers, by default, .NET will do, or try to do exactly what you tell it to do?  If you tell it to do the impossible, it will do the next […]
  • Readonly variables in CSharp? Really?!Readonly variables in CSharp? Really?! I'm sure most of you are familiar with the keyword "const," which allows you to declare a variable and give it a value and assures that no other code will change the value. const int v = […]
  • Stackalloc in CSharpStackalloc in CSharp In the last few weeks we've looked at several keywords from the CSharp language that allow us to deal with memory management directly.  Stackalloc is another keyword from that […]

About Dave Bush

Dave Bush is a Full Stack ASP.NET developer focusing on ASP.NET, C#, Node.js, JavaScript, HTML, CSS, BootStrap, and Angular.JS.Does your team need additional help in any of the above? Contact Dave today.

One Pingback/Trackback

  • http://www.electricbiro.co.uk Robert Stevenson-Leggett

    Good info.

    You can also stack using statements of different types.

    A common example is:

    string connString = config.ConnectionString;

    using(SqlConnection conn = new SqlConnection(connString))
    using(SqlCommand cmd = conn.CreateCommand())
    {
    //Do database stuff here.
    }

    Cheers.
    Rob.

  • Pingback: Dew Drop - November 11, 2008 | Alvin Ashcraft's Morning Dew()