Using statement vs. IDisposable.Dispose()

oscilatingcretin picture oscilatingcretin · Jun 11, 2012 · Viewed 34.4k times · Source

It has been my understanding that the using statement in .NET calls an IDisposable object's Dispose() method once the code exits the block.

Does the using statement do anything else? If not, it would seem that the following two code samples achieve the exact same thing:

Using Con as New Connection()
    Con.Open()
    'do whatever '
End Using

Dim Con as New Connection()
Con.Open()
'do whatever '
Con.Dispose()

I will give the best answer to whoever confirms that I am correct or points out that I am wrong and explains why. Keep in mind that I am aware that certain classes can do different things in their Dispose() methods. This question is about whether or not the using statement achieves the exact same result as calling an object's Dispose() method.

Answer

Brian Warshaw picture Brian Warshaw · Jun 11, 2012

using is basically the equivalent of:

try
{
  // code
}
finally
{
  obj.Dispose();
}

So it also has the benefit of calling Dispose() even if an unhandled exception is thrown in the code within the block.