What's the point of overriding Dispose(bool disposing) in .NET?

Mark Carpenter picture Mark Carpenter · Feb 25, 2009 · Viewed 33.1k times · Source

If I write a class in C# that implements IDisposable, why isn't is sufficient for me to simply implement

public void Dispose(){ ... } 

to handle freeing any unmanaged resources?

Is

protected virtual void Dispose(bool disposing){ ... }

always necessary, sometimes necessary, or something else altogether?

Answer

Jon Skeet picture Jon Skeet · Feb 25, 2009

The full pattern including a finalizer, introduction of a new virtual method and "sealing" of the original dispose method is very general purpose, covering all bases.

Unless you have direct handles on unmanaged resources (which should be almost never) you don't need a finalizer.

If you seal your class (and my views on sealing classes wherever possible are probably well known by now - design for inheritance or prohibit it) there's no point in introducing a virtual method.

I can't remember the last time I implemented IDisposable in a "complicated" way vs doing it in the most obvious way, e.g.

public void Dispose()
{
    somethingElse.Dispose();
}

One thing to note is that if you're going for really robust code, you should make sure that you don't try to do anything after you've been disposed, and throw ObjectDisposedException where appropriate. That's good advice for class libraries which will be used by developers all over the world, but it's a lot of work for very little gain if this is just going to be a class used within your own workspace.