Does connection close when command is disposed and the connection is defined directly on the command?

StackOverflow https://stackoverflow.com/questions/410222

  •  03-07-2019
  •  | 
  •  

Question

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
}
Was it helpful?

Solution

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

OTHER TIPS

No, the connection object will not be disposed until you dispose it explicitly. But my recommendation is to use using blocks whenever you can.

It does not close the connection, you need to either close it yourself or put it in its own using statment.

Also here is a tip to make your using blocks a bit more readable:

using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand())
{
    cmd.Connection = conn;
}

@milot

But my recommendation is to use using blocks whenever you can.

Using Using Blocks is nice but useless when working with non IDisposable Objects and so this can be confusing if you use Using Blocks anywhere.

Be careful since your objects might not being Disposed if they don't implements IDisposable.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top