0

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;
    }
}
James Madison
  • 337
  • 1
  • 4
  • 17
  • 1
    This is not an attribute, it's just a private field. You should implement IDisposable in DatabaseManager and dispose connection. – Dennis Mar 02 '16 at 18:17

2 Answers2

2

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.

Tony Vitabile
  • 8,298
  • 15
  • 67
  • 123
  • DatabaseManager does not implement IDisposable, should it? – James Madison Mar 02 '16 at 18:16
  • 1
    If you're going to use it in a `using` statement, it has to. The compiler won't let you use it in a `using` statement unless it implements `IDisposable`. And given what you're trying to do, it definitely should. – Tony Vitabile Mar 02 '16 at 18:17
  • Don't forget to close the sql connection on the dispose method of your DatabaseManager class like Tony said. – RiceRiceBaby Mar 02 '16 at 20:16
2

It can but you have to write the code to do it. Here is your example with the DatabaseManager now implementing IDisposable. Before the using statement would have given you a compile time error because it did not implement that.

Also the _connection below is called a field, not an attribute which is something else entirely.

Before you start to implement IDisposable in your types please refer to the proper way to implement IDisposable, like it should never throw an exception. Here is the Microsoft take on the Dispose pattern, its a great checklist of what to do and what to avoid.

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

public class DatabaseManager : IDisposable
{
    private SqlConnection _connection;

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

    // basic implementation of IDisposable
    public void Dispose() {
        _connection.Dispose();
    }
}
Igor
  • 60,821
  • 10
  • 100
  • 175
  • 1
    That link to the MSDN article on how to implement the Disposable pattern is handy and something I hadn't read before. – Tony Vitabile Mar 02 '16 at 18:40