I commonly run into the need to implement IDisposable in my code. To correctly dispose of both managed and unmanaged resources requires a reasonable amount of boilerplate code. Based on the documentation found here I have created the following base class.
My intent is that any object I create that needs to dispose of resources doesn't need to rewrite the boilerplate code. Rather it can inherit from this object and implement two abstract methods.
Does this appear correct? And has anyone else written something similar? I would appreciate comments on the style, correctness and how well this conforms to best practices.
public abstract class DisposableObject : IDisposable
{
private bool _disposed = false;
public bool Disposed
{
get { return _disposed; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~DisposableObject()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
DisposeManagedResources();
}
DisposeUnmanagedResources();
_disposed = true;
}
}
protected abstract void DisposeManagedResources();
protected abstract void DisposeUnmanagedResources();
}
EDIT: Final Implementation
public abstract class DisposableObject : IDisposable
{
public bool Disposed { get; private set;}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~DisposableObject()
{
Debug.Assert(Disposed, "WARNING: Object finalized without being disposed!");
Dispose(false);
}
private void Dispose(bool disposing)
{
if (!Disposed)
{
if (disposing)
{
DisposeManagedResources();
}
DisposeUnmanagedResources();
Disposed = true;
}
}
protected virtual void DisposeManagedResources() { }
protected virtual void DisposeUnmanagedResources() { }
}