49

I'm using this code:

public void InsertMember(Member member)
{
    string INSERT = "INSERT INTO Members (Name, Surname, EntryDate) VALUES (@Name, @Surname, @EntryDate)";

    using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))
    {
        sqlConnection.Open();

        using (SqlCommand sqlCommand = new SqlCommand(INSERT, sqlConnection))
        {
            sqlCommand.Parameters.Add("@Name", SqlDbType.VarChar).Value = member.Name;
            sqlCommand.Parameters.Add("@Surname", SqlDbType.VarChar).Value = member.Surname;
            sqlCommand.Parameters.Add("@EntryDate", SqlDbType.Date).Value = member.EntryDate;

            sqlCommand.ExecuteNonQuery();
        }
    }
}

It's not showing any errors or problems at all. Is it wrong if I don't add sqlConnection.Close(); before disposing of it? If yes, why?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Etrit
  • 865
  • 2
  • 14
  • 25
  • 4
    The using statement will `Dispose` the connection even in case of an exception, so you don't really need a `Close` call there – V4Vendetta Sep 03 '13 at 09:03

7 Answers7

61

There is no need to Close (or Dispose) here; the using block will take care of that for you.

As stated from Microsoft Learn:

The following example creates a SqlConnection, opens it, [and] displays some of its properties. The connection is automatically closed at the end of the using block.

private static void OpenSqlConnection(string connectionString) 
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
        Console.WriteLine("State: {0}", connection.State);
    } 
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Darren
  • 68,902
  • 24
  • 138
  • 144
  • 2
    Is it OK if the code has a connection.Close(); just before your second last curly brace '}'? Will this throw an exception when the using block tries to close a connection that is already closed by code? – variable Aug 18 '14 at 07:17
11

According to the Microsoft Learn documentation for the Close method:

you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent.

Therefore, calling Dispose (implicitly so, even, using using) will cover your bases, as it were.

It's worth noting, too, I think,though not specific to your case, that Close will always effectively be called when the thing is wrapped in a using statement - which might not be the case should it be omitted and an exception occur without the proper try/catch/finally handling.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
  • 1
    In the example it states: The following example creates a SqlConnection, opens it, displays some of its properties. The connection is automatically closed at the end of the using block. – Darren Sep 03 '13 at 09:03
  • @DarrenDavies Precisely. It's more explicit on the details even further up than that. – Grant Thomas Sep 03 '13 at 09:04
11

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. MSDN

So ultimately your code line

using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))

will be converted into a normal try finally block by compiler calling IDisposable object in the finally.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Suraj Singh
  • 4,041
  • 1
  • 21
  • 36
5

Is it wrong if I don't add sqlConnection.Close(); before disposing it

No, it is not as long as you are using your connection within Using. When you will leave the using scope, Dispose will be called for sql connection. which will close the existing connection and free-up all the resources as well.

Ehsan
  • 31,833
  • 6
  • 56
  • 65
4

The using statement is a try finally block and in your case the final block would have a connection.Dispose() call. So you don't really need a independent connection.Close() statement there.

The advantage is that this ensures the disposal even in case of an exception since the finally block will always run.

try
{
sqlConnection.Open();
// ....
}
finally
{
if(sqlConnection != null)
      sqlConnection.Dispose();
}
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
3

No, it is not wrong. The sqlConnection will close the connection after it will pass using block and call Dispose method. SqlConnection.Dispose() equal to SqlConnection.Close() method.

From MSDN: If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent.

Alex
  • 8,827
  • 3
  • 42
  • 58
3

You are using a Using which will Dispose() the object for you.

If you take the connection outside of the Using statement, then yes - you would need to close the connection when finished.

Hexie
  • 3,955
  • 6
  • 32
  • 55