For ideas on when to implement IDisposable, see another of my blog posts, Implement IDisposable More.
If you decide that your class should implement IDisposable, you have done your part to be sure that resources can be cleaned up immediately with a call you your Dispose method.
However, what if another object fails to call your Dispose method? Your Dispose method will never run.
In most cases, if a Dispose method does not run, I consider it a coding error. To catch it, I developed this simple enforcement trick:
public class SomeDisposableClass: IDisposable
myStreamReader = new StreamReader(“c:\foo.txt”);
public void Dispose()
isDisposed = true;
if (myStreamReader != null)
Console.WriteLine(“An instance of SomeDisposableClass was not disposed before garbage collection.”);
A private field called isDisposed defaults to false, but is set to true if the Dispose method runs. If the Dispose method does not run, a finalizer catches the coding error by outputting a message to the console window.
Objects with finalizers pay a garbage collection performance penalty. To avoid that penalty, the above code only compiles in the finalizer in debug mode.
Typically, you can spot these error messages in the console window when garbage collection runs at application shut-down. However, they can show up at any time if your object is garbage collected sooner.
If you really want to enforce that your Dispose methods get called, throw an exception instead of outputting a message to the console window.
Be careful what you do in your finalizer. The finalizer will run on a garbage-collection thread, so avoid the temptation to reference any non-thread-safe fields. While it would be nice to pop up a message box to report not-disposed errors, during application shutdown, you may or may not catch a glimpse of it before shutdown completes.
Please add comments to refine the use of IDisposable or to show support for this enforcement trick.