The using block

There’s something about the using block (that’s been around in C# since its creation, and it’s now a new feature in VB 2005) that I never quite got it.
 
The using block is supposed to always call the Disposable method on a object automatically at the end of the block. However, what if something bad happen on that code and an exception is thrown? For instance let’s say we have the following class:
 

 class MyClass : IDisposable
 {

  #region IDisposable Members

  public void Dispose()
  {
   Console.WriteLine("Disposing…");
  }

  #endregion
 }

 
And then we use that class like so:
 
using (MyClass foo = new MyClass())
{
    throw new Exception("Forcing an exception…");
}
 
In such case, the Dispose method never gets called. That means we’d have to wrap that code up in a try/catch/Finally block, and call the Dispose method manually on the Finally block, defeating the purpose of the using block.
 
For that reason, instead of going that route, I’ve actually just been taking care of that myself, like so:
 

   MyClass foo = null;

   try
   {
    foo = new MyClass();
    throw new Exception("Forcing an exception…");
   }
   catch
   {
    Console.WriteLine("Catching…");
   }
   finally
   {
    Console.WriteLine("Finally…");

    if (foo != null)
    {
     foo.Dispose();
    }
   }

 
That way I’m pretty sure that the Dispose method gets called no matter what (provided that the object doesn’t have a null reference).
 
Maybe somebody could jump in here and give us some insight in case I’m overlooking something here.
Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: