locked
Closing SqlConnection when having it inside a using( ) statement? RRS feed

  • Question

  • hello,

    Do I still need to close a SqlConnection within a using() statement or does using take care of closing and disposing by itself?

    Literally the same question could be asked regards StreamWriter etc.

    May I conclude that any unmanaged class that is implementing IDisposable interface, is automatically closed, when i am having it inside a using() statement?

    Thanks



                using (SqlConnection connection = new SqlConnection(connStr)) 
                { 
                    connection.Open(); 
                     
                    //DoWork 
     
                    connection.Close(); // Do I still have to do this? 
                } 

    Saturday, February 14, 2009 1:19 PM

Answers

  • SqlConnection.Dispose() calls Close().  So, no, you don't have to.  This is the normal pattern throughout the framework, Dispose() does whatever is required to really dispose the resources, no matter what state the object is in.
    Hans Passant.
    • Marked as answer by Kave Saturday, February 14, 2009 1:55 PM
    Saturday, February 14, 2009 1:49 PM

All replies

  • As the ressource cleanup is done by the Garbage collection you don't know when the cleanup is really done.
    Saturday, February 14, 2009 1:42 PM
  • SqlConnection.Dispose() calls Close().  So, no, you don't have to.  This is the normal pattern throughout the framework, Dispose() does whatever is required to really dispose the resources, no matter what state the object is in.
    Hans Passant.
    • Marked as answer by Kave Saturday, February 14, 2009 1:55 PM
    Saturday, February 14, 2009 1:49 PM
  • Many Thanks.
    Saturday, February 14, 2009 1:56 PM