Per my other question here about Disposable objects, should we call Close() before the end of a using block?
using (SqlConnection connection = new SqlConnection())
using (SqlCommand command = new SqlCommand())
{
command.CommandText = "INSERT INTO YourMom (Amount) VALUES (1)";
command.CommandType = System.Data.CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
// Is this call necessary?
connection.Close();
}
Since you have a using block, the Dispose method of the SQLCommand will be called and it will close the connection:
No, having the Using block calls
Dispose()
for you anyway, so there is no need to callClose()
.Using Reflector, you can see that the
Dispose
method ofSqlConnection
actually does callClose()
;No, the SqlConnection class inherits from IDisposable, and when the end of using (for the connection object) is encountered, it automatically calls the Dispose on the SqlConnection class.
No, calling Dispose() on SqlConnection also calls Close().
MSDN - SqlConnection.Dispose()
Disassembly of SqlConnection from using .NET Reflector:
It calls Close() inside of Dispose()