Are resources disposed even if an exception is thrown in a using block?

Dot NET picture Dot NET · Nov 23, 2011 · Viewed 9.4k times · Source

Possible Duplicate:
Does Dispose method still get called when Exception is thrown inside of Using statment?

I've got a number of using blocks, when accessing a database. I was wondering - if an exception had to be thrown within the using block, would the necessary resources still be disposed, even though the end of the block is not reached? Or would I need to close them myself manually in the catch block?

Answer

CodeZombie picture CodeZombie · Nov 23, 2011

The resources defined with the using statement were disposed, this is the main reason what using is good for.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
http://msdn.microsoft.com/en-us/library/yh598w02%28v=VS.100%29.aspx