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

Yes using wraps your code in a try/finally block where the finally portion will call Dispose() if it exists. It won't, however, call Close() directly as it only checks for the IDisposable interface being implemented and hence the Dispose() method.

Yes, using wraps your code in a try/finally block where the finally portion will call Dispose() if it exists. It won't, however, call Close() directly as it only checks for the IDisposable interface being implemented and hence the Dispose() method. See also: stackoverflow.com/questions/220234/inter... stackoverflow.com/questions/141204/what-... stackoverflow.com/questions/149609/c-usi... stackoverflow.com/questions/317184/c-usi... stackoverflow.com/questions/278902/using... http://stackoverflow.com/questions/212198/what-is-the-c-using-block-and-why-should-i-use-it http://stackoverflow.com/questions/513672/disposable-using-pattern http://stackoverflow.com/questions/376068/does-end-using-close-an-open-sql-connection.

Just to point out on the connection classes if you reflector over them you will see Dispose() does indeed internally call Close(). If it's in a state it can. – Chris Marisic Feb 6 '09 at 14:37 You are correct, it does.

However, I deliberately didn't mention it as I didn't want to mislead anyone to think this has anything to do with IDisposable or the associated pattern. The fact that this particular implementation calls Close() is a detail of the implementation, not the pattern. – Jeff Yates Feb 6 '09 at 22:01.

This is how reflector decodes the IL generated by your code: private static void Main(string args) { SqlConnection conn = new SqlConnection("..."); try { conn.Open(); DoStuff(); } finally { if (conn! = null) { conn.Dispose(); } } } So the answer is yes, it will close the connection if DoStuff() throws an exception.

Add if conn.Open() throws an exception. :D – Jeff Yates Feb 5 '09 at 23:07 Yeah sure. If whatever is in the block AFTER the using clause throws an exception, the connection will be closed.

The only way the finally block won't be executed is if the "new SqlConnection(...)" throws, but in that case you wouldn't have actually a valid open connection to close. So it's fine. – Florin Sabau Feb 5 '09 at 23:15.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions