cpeterso.com > IDisposable for Mortals
This web page contains yet another example of the IDisposable interface for Microsoft's .NET Framework using C#. Read Joe Duffy's "Dispose, Finalization, and Resource Management" Design Guidelines. You will probably agree that implementing IDisposable and finalizers is a daunting task.
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 implement 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, then there is no reason to define a finalizer. There is nothing your finalizer can do! You are not allowed to touch any managed resources in a finalizer because 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)