I know that a lot of examples exist where a SqlConnection is defined and then a SqlCommand is defined, both in Using blocks:
using (var conn = new SqlConnection(connString)) { using (var cmd = new SqlCommand()) { cmd.Connection = conn; //open the connection } }
My question: If I define the connection directly on the SqlCommand, does the connection close when the command is disposed?
using (var cmd = new SqlCommand()) { cmd.Connection = new SqlConnection(connString); //open the connection }
No, SqlCommand never attempts to close/dispose of the connection.