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:

  1. public class DisposableClass : IDisposable
  2. {
  3. public void Dispose()
  4. {
  5. //The usual cleanup
  6. #if DEBUG
  7. GC.SuppressFinalize(this);
  8. #endif
  9. }
  10. #if DEBUG
  11. ~DisposableClass()
  12. {
  13. Debug.Fail(string.Format("Undisposed {0}", GetType().Name));
  14. }
  15. #endif
  16. }

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.