.NET Answers

ASP.NET, HTML, CSS, Visual Studio, CSharp, VB.NET and other programming items of interest.
Subscribe
  • Home
  • About Me
  • Advertising
  • Click Here to Ask a question
    • Privacy Policy
  • Site Map

Dispose with Using

November 10, 2008 By: Dave

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
  • Two Interfaces. Same Method. Two meanings. - September 29th, 2008
  • Making values nullable - October 9th, 2008
  • CSharp's Property Shortcuts - October 23rd, 2008
  • Readonly variables in CSharp? Really?! - October 29th, 2008
  • Dispose with Using - November 10th, 2008
  • Delegates in .NET - December 4th, 2008
  • Using Sealed in CSharp - December 8th, 2008
  • CSharp checked and unchecked - December 11th, 2008
  • Advanced CSharp - unsafe mode - December 15th, 2008
  • Volatile variables and CSharp threads - December 22nd, 2008
  • What is the global keyword in CSharp? - December 29th, 2008
  • CSharp fixed keyword - January 5th, 2009
  • using - There's more there than you are using - February 2nd, 2009
  • Stackalloc in CSharp - February 16th, 2009
  • Removing Warnings from CSharp Compile Cycle - March 10th, 2009
  • && vs & and | vs ||... What's the difference? - March 16th, 2009
  • Advanced CSharp - yield - March 25th, 2009
  • Just say “No!” to C# Regions? Really?! - April 16th, 2009
  • C# “” better than string.Empty? - April 20th, 2009
  • .Net String Pool – Not Just For The Compiler - April 22nd, 2009
  • CSharp ?? Operator - May 18th, 2009
  • Using VB.NET From CSharp - July 1st, 2009

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

Related Post

  • using – There’s more there than you are using
  • Using VB.NET From CSharp
  • iTextSharp – Adding Images
Bookmark to:

Add to Del.icio.us Add to digg Add to DotNetKicks Add to DZone Add to Facebook Add to Slashdot Add to Stumble Upon Add to Technorati
Hide Sites
Tags: csharp, dispose, using

2 Responses to “ Dispose with Using ”

  1. # 1 Robert Stevenson-Leggett Says:
    November 10th, 2008 at 7:50 am

    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.

  2. # 2 Dew Drop - November 11, 2008 | Alvin Ashcraft's Morning Dew Says:
    November 11th, 2008 at 8:42 am

    [...] Dispose with Using (Dave M. Bush) [...]

← Friday Books – "Beginning ASP.NET 3.5 in C# 2008"
VS2008 SP1 Hotfix to Support "-vsdoc.js" IntelliSense Doc Files →
  • Search

  • Subscribe

    U COMMENT
    I FOLLOW

    Subscribe in a reader

    OR

    Subscribe via e-mail

    Enter your email address: 

    Delivered by FeedBurner

     

  • Follow Me

    • Twitter
    • FaceBook
    • Digg
    • StumbleUpon
    • Propeller
    • Delicious
    • Plaxo

     

  • Recent Posts

    • ASUS Eee PC 1005HA-PU1X-BK Black Netbook
    • jQuery – Date Picker
    • Using VB.NET From CSharp
    • iTextSharp – Adding Images
    • Hungarian Notation – Use What Works, Spit Out The Bones
    • Pre Order Windows 7
    • jQuery Dialog – With Validation Controls
    • iTextSharp – The easy way
    • Structure of my ASP.NET Web Applications
    • 35% Off Accronis True Image 2009 Home
    • VB.NET Hide Module Name
    • ASP.NET/VB.NET – Video Training
    • Does jQuery Make Us Lazy?
    • PDFs Using iTextSharp
    • Programming SEO – Ping



  • Advertise on this site through Lake Quincy Media
  • DotNetNuke Sponsor

     

    Most Valuable Blogger
  • Sponsor

  • Categories

    • Advanced CSharp
    • Advanced VB.NET
    • ASP.NET MVC
    • Did you know
    • DotNetNuke – Module Development
    • DotNetNuke – Skinning
    • internationalization
    • iTextSharp
    • jQuery
    • none
    • Seach Engine Optimization
    • Silverlight
    • SQL For Programmers
    • Twitter
    • winforms
  • Cloud

    .net ajax architecture asp.net book books containers csharp css dal dataset datasets dotnetnuke events gridview images internationalization internet explorer javascript jQuery json linq listview modules ms-sql MVC objectdatasource programming reflection seo Silverlight skinning sql testing tsql tutorial Twitter twitterizer vb.net video view Vista visual studio webservice WordPress
  • Archives

    • July 2009
    • June 2009
    • May 2009
    • April 2009
    • March 2009
    • February 2009
    • January 2009
    • December 2008
    • November 2008
    • October 2008
    • September 2008
    • August 2008
    • July 2008
    • June 2008
    • May 2008
    • April 2008
    • March 2008
    • February 2008
    • January 2008
    • December 2007
    • November 2007
    • October 2007
  • Meta

    • Log in
    • Entries RSS
    • Comments RSS
    • WordPress.org
    • Privacy Policy
  • Calendar

    November 2008
    S M T W T F S
    « Oct   Dec »
     1
    2345678
    9101112131415
    16171819202122
    23242526272829
    30  
  • Blogroll

    • Alvin Ashcraft’s Morning Dew
    • ASP.NET Consulting
    • Life Hacker
    • Remember Anything
    • The Price of Their Toys
    • Uncategorized Thought


.NET Answers © 2007 - 2008 All Rights Reserved.
Entries and Comments.