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.
See more on this question at Stackoverflow