Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlConnection.ServerVersion Exception after Close()

Tags:

c#

.net

asp.net

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)

like image 587
RealWorldCoder Avatar asked Jul 16 '26 07:07

RealWorldCoder


2 Answers

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.

like image 138
Jon Skeet Avatar answered Jul 17 '26 19:07

Jon Skeet


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.

like image 40
SLaks Avatar answered Jul 17 '26 21:07

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!