IDisposable Made E-Z

September 21, 2006 Steve Hawley

Joe Duffy wrote this extensive entry about IDisposable and how it should be implemented under many different circumstances.  It's great, it's complete, it's probably more than what most people need to look at.

Here is a pattern you can use for your code that sums all that up for you.  Just paste this in to your class that implements IDisposable:

private bool _disposed = false;

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this); // this line added 10/4 (oops)
}

protected virtual void Dispose(bool disposing)
{
    if (!_disposed)
    {

        if (disposing)
        {
            DisposeManagedResources();
        }
        DisposeUnmanagedResources();
        _disposed = true;
    }
}

protected virtual void DisposeManagedResources() { }
protected virtual void DisposeUnmanagedResources() { }
private ~FIXME() // put in your class name
{
    Dispose(false);
}


The biggest problem with the IDisposable pattern as defined by Microsoft is that it contains 5 variations on the word 'dispose' that nearly all mean different things.  The code reads like a lesson in conjugation.

So here's what I did - I broke it down into two actions that you really care about: disposing your managed resources and disposing your unmanaged resources.  So if your class keeps other classes that are IDisposable, you call their Dispose() method from DisposeManagedResources().  If your class holds resources from the unmanaged world, you get rid of them in DisposeUnmanagedResources().

I made them virtual so that you can subclass your class and override those methods easily enough (don't forget to call the base class!).  If you don't want this ability, take out virtual and make them private.

PS - Joe - you and Joel promised me a copy of your book for catching the typo in the GFN segment at PDC.

About the Author

Steve Hawley

Steve has been with Atalasoft since 2005. Not only is he responsible for the architecture and development of DotImage, he is one of the masterminds behind Bacon Day. Steve has over 20 years of experience with companies like Bell Communications Research, Adobe Systems, Newfire, Presto Technologies.

Follow on Twitter More Content by Steve Hawley
Previous Article
Anatomy of a Feature Request
Anatomy of a Feature Request

Creating a product that is an API presents many challenges as an...

Next Article
Compilers as a Commodity

Try any of our Imaging SDKs free for 30 days with Full Support

Download Now