Search code examples
c#objectdisposeusingusing-directives

Do objects with SqlConnecions as private fields get closed if the object is in an using block?


I know that using an SqlConnection inside a using block like below will close the connection at the end of the using block.

using (var connection = factory.NewSqlConnection())
{
    //code
}

I want to know if an object that has a SqlConnection private field, and is used in a using statement will also close the connection like so:

using (var db = factory.NewDatabaseManager())
{
    //code
} 

public class DatabaseManager
{
    private SqlConnection _connection;

    public DatabaseManager(SqlConnection connection)
    {
         _connection = connection;
    }
}

Solution

  • If I understand you correctly, the DatabaseManager class is used inside of a using statement, so it must implement IDisposable, and therefore has a Dispose method of its own.

    In that case, the SqlConnection object will be disposed only if the Dispose method in your DatabaseManager class calls the SqlConnection object's Dispose method. There's no magic that makes this happen. Your code has to manage the SqlConnection properly or you will have problems.