[ACCEPTED]-Close SqlConnection in the Finally when using "Using-sql

Accepted answer
Score: 15
using (var conn = new SqlConnection(_dbconnstr)) 
{
    //code
}

is expaded to:

SqlConnection conn = new SqlConnection(_dbconnstr);
try
{
    //code
}
finally
{
    conn.Dispose();
}

So you should handle errors 1 but you can forget about closing connection.

Score: 8

You don't need to close conn in the finally block. The 8 using block will handle closing the connection 7 for you. (In fact, you probably don't need 6 the try...finally at all in this case, unless you have 5 other resources that need dealing with in 4 the finally.)

The using block will translate to something 3 like this:

var conn = new SqlConnection(/*...*/);
try
{
    // ...
}
finally
{
    if (conn != null)
        ((IDisposable)conn).Dispose();
}

The Dispose method of the SqlConnection object will 2 be called in the finally block, and the Dispose method 1 goes on to call Close for you.

Score: 2

Exiting a using block calls .Dispose() on the object, for 2 a SqlConnection will close the connection and any open 1 resources.

So the try, finally block is not needed.

Score: 2

AFAIK, the following using statement:

using (var conn = new SqlConnection(_dbconnstr)) 
{

}

Is 1 equivalent to:

SqlConnection conn;
try
{
    //`using` scope operations are executed here
    conn = new SqlConnection(_dbconnstr));

}
catch
{
    //exceptions are bubbled
    throw;
}
finally
{
    //Dispose is always called
    conn.Dispose();
}
Score: 1

As per my understanding Dispose() method 2 of connection object will close the Connection. You 1 don't need to call Connection.Close explicitly.

Score: 1

The way you are closing the connection with 2 Using is Ok. Perhaps you might have forgotten 1 to close some DataReaders instead ?

More Related questions