cpeterso.com > IDisposable for Mortals
This web page contains yet another example of the IDisposable interface for Microsoft's .NET Framework using C#. Implementing IDisposable and finalizers is a daunting task. If you don't believe me, read Joe Duffy's "Dispose, Finalization, and Resource Management" Design Guidelines.
IDisposable is contagious: if a class has any IDisposable member variables, it should be IDisposable and dispose of its member variables. This abstraction leak can require some unexpected classes to be IDisposable because some of their private member variables are IDisposable.
You can copy and paste my Disposable class as a boilerplate for your classes that implement IDisposable. My Disposable class contains debug code to find common IDisposable bugs, such as "leaked" objects that have not been disposed and classes whose override void Dispose(bool disposing) forgot to call base.Dispose(disposing).
Better yet, if your class does not derive from any base classes, you can derive from my Disposable class. Your class just needs to override void Dispose(bool disposing), cleanup your managed resources (i.e. dispose of your IDisposable member variables), and call base.Dispose(disposing).
If your class (like 99% of all classes) does not contain any unmanaged resources, there is no reason to define a finalizer. There is nothing your finalizer can do! Your finalizer is not allowed to touch any (managed code) member variables because (surprisingly) they might have already been finalized. You can't even call Dispose() on your IDisposable member variables.
In the rare case your class contains unmanaged resources (like OS handles), then you should probably use SafeHandle instead of writing your own finalizer. It's easier and safer.
Disposable.cs (version 2008-01-18)