I open a SqlConnection.
SqlConnection Conn = new SqlConnection(...);
Conn.Open();
...
Conn.Close();
Conn.Dispose();
//debugger breakpoint
When I look in my debugger at this breakpoint, the Conn.ServerVersion throws a Sql exception:
Connection Closed
Of course I closed the connection, as I should, but is this exception just something to ignore? Or am I supposed to be doing it differently if I wanted to avoid getting this exception, what would I need to do besides keep it open?
My understanding is not to have any exceptions in my code, but I may be wrong. (I am new)
Just avoid examining the connection object after you've disposed of it. ("Doctor, it hurts when I do this..." "Stop doing that then!") The easiest - and most reliable - way to do that is to use a using statement instead:
using (var conn = new SqlConnection(...))
{
conn.Open();
...
}
Then conn will be out of scope after it's been disposed anyway. Note that you don't need to call Close() as well as dispose - and note the more conventional name for the local variable.
You don't actually have a problem.
As you noticed in your question, you can't get the server version from a closed connection.
When you look at that property in the debugger, you will therefore get an exception.
As long as you don't try to access it in actual code from a closed connection, you're perfectly fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With