If an exception occurs inside a "using" block, is the Dispose method called?
.net, c#, dispose, exception, using
Solution
Yes it will get called.
`using` translates into `try-finally` block, so even in case of recoverable exception `Dispose` gets called.
See: using statement C#
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.
Consider `SqlConnection` which implements `IDisposable` interface, so the following:
using (SqlConnection conn = new SqlConnection("connectionstring"))
{
//some work
}
Would get translated into
{
SqlConnection conn = new SqlConnection("connectionstring");
try
{
//somework
}
finally
{
if (conn != null)
((IDisposable)conn).Dispose(); //conn.Dispose();
}
}
Problem
In C#, if an exception occurs inside a "using" block, does the Dispose method get called?
Related problems
- Using statement vs. IDisposable.Dispose()
- Does Dispose still get called when exception is thrown inside of a using statement?
- Is there a situation in which Dispose won't be called for a 'using' block?
- Does Dispose still get called when exception is thrown inside of a using statement?
- Is there a situation in which Dispose won't be called for a 'using' block?