Welcome to Atalasoft Community Sign in | Help

IDisposable Made E-Z

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()
    GC.SuppressFinalize(this); // this line added 10/4 (oops)

protected virtual void Dispose(bool disposing)
    if (!_disposed)
        if (disposing)
        _disposed = true;

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

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.
Published Thursday, September 21, 2006 1:34 PM by Steve Hawley


Friday, April 04, 2008 10:06 AM by Rick Minerich's Development Wonderland

# .NET Memory Managment: Part 1 - Basic Housekeeping

This is the first in a series of posts I will be writing about managing memory in .NET. Before I move

Friday, June 26, 2009 11:32 AM by Steve's Tech Talk

# Using, Lambda, and RAII

One of the things like most about C++ for production coding is RAII.  I can make an object on the

# Does every user defined class needs to implement IDisposable | C Language Development | C Programming Language Tutorial

Anonymous comments are disabled