tags:

views:

71

answers:

1

Hi All,

If I have something like this:

using( SqlCommand sqlCmd = CreateSqlCommand( "load_collection_get", false ) )
{
    // Code
}

CreateSqlCommand looks like:

public static SqlCommand CreateSqlCommand( string storedProc, bool transaction )
    {
        SqlCommand sqlCmd = new SqlCommand( storedProc, sqlHelper.GetConnection() );

        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;

        if( transaction )
            sqlCmd.Transaction = sqlHelper.GetTransaction();

        return ( sqlCmd );
    }   

SqlHelper.GetConnection() returns an opened SqlCommand object

At the end of the using( SqlCommand ... ) will that close the connection for me? Or do i still need to call SqlConnection.Close before the end of the using?

+2  A: 

No, you'll still have to close the SqlConnection yourself, the using there will only dispose of the SqlCommand object.

I tend to think about it like this: you may need the connection to be open for multiple commands, perhaps all running within an SqlTransaction. If disposing of the first command closed the connection then you'd have no way to run the subsequent commands, let alone commit the transaction.

Dave
+1. It is worth stressing that Dispose of SqlCommand does not close the connection, this is, I assume, because it may not be the only thing operating on this connection.
Yossi Dahan
ok thanks, not the answer i was hoping for, but can aee why it is the case, another using(SqlConnection ...) required me thinks!!
Jay
@Yossi Dahan absolutely, plus you may need more than one command to operate on the connection (perhaps all encased within an SqlTransaction). I've updated my answer to include that.
Dave