If I write a class in C# that implements IDisposable, why isn\'t is sufficient for me to simply implement
public void Dispose(){ ... }
to han
It's not strictly necessary. It is part of the recommended Disposable pattern. If you haven't read the Framework Design Guidelines section on this (9.3 in the first edition, don't have the second edition handy sorry) then you should. Try this link.
It's useful for distinguishing between disposable cleanup and finalizable garbage-collection-is-trashing-me.
You don't have to do it that way but you should read up on it and understand why this is recommended before discounting it as unnecessary.
If a class implements IDisposable.Dispose()
and a derived class needs to add additional logic, that class must expose some kind of Dispose
method that the derived class can chain to. Since some classes may implement IDisposable.Dispose()
without having a public Dispose()
method, it's useful to have a virtual method which will be protected
in all implementations of IDisposable
regardless of whether they have a public Dispose
method or not. In most cases, the bool
argument isn't really meaningful but should be thought of as a dummy argument to make the protected virtual Dispose(bool)
have a different signature from the may-be-or-maybe-not-public Dispose()
.
Classes which doesn't use a protected virtual Dispose(bool)
will require derived classes to handle their cleanup logic in a fashion which differs from the convention. Some languages like C++/CLI which are only equipped to extend IDisposable
implementations which follow that convention may be unable to derive classes from non-standard implementations.