Search code examples
c#sqldisposesqlconnectionsqlcommand

Using when working with SQLCommand/Connection


I`ve used a function to open sql connection and generate a command.So I don`t use using for them. But what happens if I get an exception ?while catch the exception nedd I explicitly dispose them?


Solution

  • using translates into try-finally block. If you don't want to use using statement then you can mimic the same using try-finally, in your case with catch just have finally block and dispose the connection there. Something like:

    {
        SqlConnection conn = new SqlConnection("your connection string");
        try
        {
            //your code
        }
        catch (SqlException se)
        {
            //handle particular exception first
        }
        catch (Exception ex)
        {
    
            //handle all other exceptions
        }
        finally
        {
            if (conn != null)
                conn.Dispose();
        }
    }
    

    That will ensure the disposal of connection in case of an exception and normal flow (when no exception occurs)