Calling Close on SqlConnection that might not be open or closed
Question
The answers to these two questions are very close to answering my own, but they don't quite get there.
- Are Open and Closed only relevant values of ConnectionState enumeration?
- Handling different ConnectionStates before opening SqlConnection
Now that I know SqlConnection
has more states than just open and closed, I wonder if I need to do this when closing a connection that isn't inside a using statement:
switch (_transactionConnection.State)
{
case ConnectionState.Broken: /*??*/ ; break;
case ConnectionState.Closed: ; break;
case ConnectionState.Connecting: /*??*/ ; break;
case ConnectionState.Executing: /*??*/ ; break;
case ConnectionState.Fetching: /*??*/ ; break;
default: _transactionConnection.Close(); break;
}
SqlConnection _transactionConnection
is not inside a using
statement because I need to Start, Commit and Rollback a transaction from outside this class. This class implements IDisposable
and the switch statement lives in Dispose(bool disposing)
MSDN says that states other than open and closed are for future versions of the product, but @Charlie says reflector shows the other states are in use.
Can anyone tell me what should replace the /*??*/
? (I expect that my final switch statement will handle the Open and Closed cases explicitly and if /*??*/
is the same for the other states, that would be my default case.)
Solution
Since you're implementing this in Dispose(), I think I would simply call _transactionConnection.Dispose();
and let the SqlConnection class do whatever it feels is appropriate. I would avoid calling Close()
here, because while it's true that currently SqlConnection.Dispose basically just closes it, that may change in the future.