Is SqlCommand.Dispose() required if associated SqlConnection will be disposed?

Viewed 35127

I usually use code like this:

using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
{
   var command = connection.CreateCommand();
   command.CommandText = "...";
   connection.Open();
   command.ExecuteNonQuery();
}

Will my command automatically disposed? Or not and I have to wrap it into using block? Is it required to dispose SqlCommand?

6 Answers

In my opinion, calling Dispose for both SqlConnection and SqlCommand is good practice, use below code

using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
try{
    using(var command = connection.CreateCommand())
    {
       command.CommandText = "...";
       connection.Open();
       command.ExecuteNonQuery();
    }
}
catch(Exception ex){ //Log exception according to your own way
    throw;
}
finally{
    command.Dispose();
    connection.Close();
    connection.Dispose();
}
Related