Ensuring that Dispose() gets called on your IDisposable types

31 May 2012

Here is a neat trick to make sure you IDisposable classes have their dispose method called. In the finalizer, call Debug.Fail and only include it in Debug builds:

public class DisposableClass : IDisposable
{
    public void Dispose()
    {
        //The usual cleanup
#if DEBUG
        GC.SuppressFinalize(this);
#endif
     }

#if DEBUG
        ~DisposableClass()
     {
        Debug.Fail(string.Format("Undisposed {0}", GetType().Name));
     }
#endif
}

This will give you an in-your-face dialog to let you know of your fail:

Assertion Failed

I can't claim that I came up with this, but I can't remember where I saw it either.

comments powered by Disqus