Creating an IDisposable class in C # that clears SqlConnection when it finishes

In response to a previous question, someone recommended:

has a SqlConnection member variable of your class, but makes the class IDisposable and removes the SqlConnection when placing the class

I put together an implementation of this proposal (see below), but I wanted to check the correctness of this implementation (obviously, he is currently doing nothing but open the connection, but the idea is that there will be methods that use the connection and which could rely on it to exist and be open).

public class DatabaseRecord : IDisposable
{
    protected SqlConnection connection;

    public DatabaseRecord()
    {
        connection = new SqlConnection("ConnectionString");
        connection.Open();
    }

    // IDisposable implementation

    private bool disposed;
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }


    private void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                connection.Dispose();
            }
            disposed = true;
        }

    }

    // Destructor
    ~DatabaseRecord()
    {
        Dispose(false);
    }
}

? , DatabaseRecord, - Dispose , / ? /, using (var connection = new SqlConnection("...")) { } , ?

+3
4

SqlConnection - if (disposing). , , , witrh a using. , using SqlConnections, , .

+4

, , , DbConnection , , , ,

using (var connection = new SqlConnection("...")) { ... }
+3

connection.Dispose() if (disposing) { ... }. Close() , Dispose() , .

+2
source

This will work, and it will be more efficient to use multiple operators. Code that uses the DatabaseRecord class can do this inside the using statement so that it automatically clears when it leaves the loop.

However, one recommendation would be to use the Dispose method to check the status of the Connection object and close it if it is still open before dispose is called.

+1
source

All Articles