Search code examples
c#.netado.netusingsqlconnection

Do I need to manually close a .NET SqlConnection, if it throws an exception inside a `using` statement?


If a SqlConnection throws an exception during execution inside a using statement, do I need to manually close the connection in a finally ? or will the scope of the using statement call the Dispose method (on the SqlConnection) for me ... which therefore executes the .Close(); method for me (automatically)?

for example:

using (var sqlConnection = new SqlConnection(_connectionString)
{
   sqlConnection.Open();

   throw new Exception("boom!");
}

vs

using (var sqlConnection = new SqlConnection(_connectionString)
{
    try
    {
        sqlConnection.Open();

        throw new Exception("boom!");
    }
    finally
    {
        sqlConection.Close();
    }
}

Also, does wrapping this in a TransactionScope + an exception is throw, affect how I should .Close() or the using scope auto-does this for me.


Solution

  • No, it is still disposed if it is within the using

    The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

    Source : MSDN.