views:

575

answers:

4

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
}
+2  A: 

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

Robert C. Barth
+2  A: 

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

milot
+2  A: 

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;
}
Andrew Hare
Very nice Andrew, I've never seen that combo before. Will have to give that a try. I've always nesting multiple "using blocks", which can make code harder to read at times.
barneytron
IMO, that makes them LESS readable. I'm OK with losing the curly's, just not the part where you're not indenting the inner using.
Robert C. Barth
A: 

@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.

Yoann. B
Hmm, I don't think the compiler will let you use "using" blocks for objects that don't implement IDisposable. I vaguely remember getting a compilation error last time I tried that, which was several years ago.
barneytron