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

abatishchev picture abatishchev · Nov 27, 2009 · Viewed 30.2k times · Source

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?

Answer

RichardOD picture RichardOD · Nov 27, 2009

Just do this:

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

Not calling dispose on the command won't do anything too bad. However, calling Dispose on it will suppress the call to the finalizer, making calling dispose a performance enhancement.