Search code examples
c#asp.netado.netsqlconnection

Do I need to close and dispose the SQLConnection explicitly?


SqlDataReader rdr = null;
con = new SqlConnection(objUtilityDAL.ConnectionString);
using (SqlCommand cmd = con.CreateCommand())
{
    try
    {
        if (con.State != ConnectionState.Open)
            con.Open();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(Parameter);
        cmd.CommandText = _query;
        rdr = cmd.ExecuteReader();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

In this above code, sqlconnection is opened inside the managed code. Hence, will the connection object be disposed automatically upon ending the scope of USING?


Solution

  • You should Dispose every temporary IDisposable instance you create manually, i.e. wrap them into using:

       // Connecton is IDisposable; we create it 
       //   1. manually - new ...
       //   2. for temporary usage (just for the query)
       using (SqlConnection con = new SqlConnection(objUtilityDAL.ConnectionString)) {
         // Check is redundant here: new instance will be closed 
         con.Open();
    
         // Command is IDisposable
         using (SqlCommand cmd = con.CreateCommand()) {
           cmd.CommandType = CommandType.StoredProcedure;
           cmd.Parameters.Add(Parameter);
           cmd.CommandText = _query;
    
           // Finally, Reader - yes - is IDisposable 
           using (SqlDataReader rdr = cmd.ExecuteReader()) {
             // while (rdr.Read()) {...}
           }
         }   
       }
    

    Please, notice that

       try {
         ...
       }
       catch (Exception ex) {
         throw ex;
      } 
    

    is at least redundant (it does nothing but rethrow the exception, while loosing stack trace) and that's why can be dropped out