C# – Does connection close when command is disposed and the connection is defined directly on the command

cusingusing-statement

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
}

Best Answer

No, SqlCommand never attempts to close/dispose of the connection.

Related Topic