views:

1465

answers:

4

If I wrap a SQLConnection in a Using, should I close it or does the end using handle it?

using cn as new system.data.sqlclient.sqlconnection()
    cn.open
    '{do a bunch of other stuff with commands and datareaders here}
    cn.close 'Do I need this?
end using
+7  A: 

Exiting a using block calls .Dispose() on the object in question (cn in your example) which for a SqlConnection will close the connection and any open resources.

matt b
In other words: YES.
Joel Coehoorn
What will happen if an exception is thrown within the using block? will the connection still get disposed?
Youssef
+5  A: 

More precisely calling Dispose or Close will mark the underlying physical connection as "Not in use" - but doesn't really close it. A "Not in use" connection that isn't yet physically closed is thus available for pooling. Therefore - calling Dispose would return a connection to the connection pool.

Darin Dimitrov
A: 

using is just a shorthand to try/finally. this is equivilent code to what you posted

Try
    SqlConnection cn as new system.data.sqlclient.sqlconnection()
    cn.open
    '{do a bunch of other stuff with commands and datareaders here}
    cn.close 'Do I need this?
Finally
    cn.Dispose()
End Try

Dispose is supposed to take care of all resource cleanup, in the case of connections it will close it.

Matt Briggs
+2  A: 

While the SQL's Dispose method does close the connection (eventually according to darin) you should leave the call to Close in there. The reason is that you would be relying on the underlying implementation of Dispose to call close. Also seeing an Open without a Close is like seeing a New without a Delete for those of us that have programmed in unmanaged languages. It's a code smell for me.

Bryan Anderson
I agree with the code smell. I like to program explicitly, not implicitly.
Redbeard 0x0A
I disagree. It's just noise. Learn the new paradigm with using blocks.
TrueWill