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();
}
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;
}
}
~DatabaseRecord()
{
Dispose(false);
}
}
? , DatabaseRecord, - Dispose , / ? /, using (var connection = new SqlConnection("...")) { } , ?