The following code doesn't have any sort of error handling.
I'm curious though. As it sits, will the connection that is created in the using statement be closed when the exception is thrown? Or will the connection remain open because it was never explicitly closed?
public override string ResetToDefault() {
string result;
using (var cn = HostFacade.GetDbConnection())
{
cn.Open();
DbProvider.Transaction = cn.BeginTransaction();
// Do something here that throws an unhandled exception.
DbProvider.Transaction.Commit();
cn.Close();
}
return result;
}
Edit: The connection being returned by HostFacade.GetDbConnection is an IDbConnection. It's safe here to assume it's being implemented as a SqlConnection object.
Yes, because a using
statement is expanded by the compiler to be a try...finally
block. Your code is the same as this:
SqlConnection cn = null;
try {
cn = HostFacade.GetDbConnection();
cn.Open();
// .. rest of the code here
}
finally {
if (cn != null)
cn.Dispose();
}
The Dispose
call will close the connection.
The CLR guarantees that a finally block will execute.. except in very specific scenarios (such as a call to FailFast
IIRC).