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 Related Items:

Kathy Smith: Build Muscle Shrink FatKathy Smith: Build Muscle Shrink FatUsing cutting-edge sculpting techniques Kathy Smith takes fat burning to the next level. Working the legs buns arms shoulders and core all at once all... Read More >
Ink Refill Kit for Canon PIXMA MX860 Printers using CLI-221 PGI-220 CartridgesInk Refill Kit for Canon PIXMA MX860 Printers using CLI-221 PGI-220 CartridgesQuick Overview:

Colors: Cyan, Magenta, Yellow, Black, Pigment Black
Volume: 120ml Per Bottle, 600ml Total
Contents: 5x Ink Bottles wi... Read More >

If you're new here, you may want to subscribe to the mailing list to get notifications of new post and a virtual tour of past topics. Thanks for visiting!

Related Post

2 Responses to “Dispose with Using”

DotNetNuke Sponsor

 

Most Valuable Blogger
Sponsor