SqlConnection.Close() inside using statement
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();
}
}
}
Is it wrong if I don't add sqlConnection.Close();
before disposing it? I mean. It's not showing any errors, no problems at all. Is it better to Close it first? If yes, why?
Solution 1:
No need to Close or Dispose
the using
block will take care of that for you.
As stated from MSDN:
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.
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);
}
}
Solution 2:
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
Solution 3:
According to MSDN 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.