Does SqlCommand.Dispose close the connection?

No, Disposing of the SqlCommand will not effect the Connection. A better approach would be to also wrap the SqlConnection in a using block as well: using (SqlConnection conn = new SqlConnection(connstring)) { conn.Open(); using (SqlCommand cmd = new SqlCommand(cmdstring, conn)) { cmd.ExecuteNonQuery(); } } Otherwise, the Connection is unchanged by the fact that a … Read more

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

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.

What is the difference between using IDisposable vs a destructor in C#?

A finalizer (aka destructor) is part of garbage collection (GC) – it is indeterminate when (or even if) this happens, as GC mainly happens as a result of memory pressure (i.e. need more space). Finalizers are usually only used for cleaning up unmanaged resources, since managed resources will have their own collection/disposal. Hence IDisposable is … Read more

Finalize vs Dispose

The finalizer method is called when your object is garbage collected and you have no guarantee when this will happen (you can force it, but it will hurt performance). The Dispose method on the other hand is meant to be called by the code that created your class so that you can clean up and … Read more