I\'m new to C#, so apologies if this is an obvious question.
In the MSDN Dispose example, the Dispose method they define is non-virtual. Why is that? It seems odd
This is certainly not an obvious one. This pattern was especially choosen because it works well in the following scenario's:
While a virtual Dispose()
method will work in the scenario where classes don't need finalization, it doesn't work well in the scenario were you do need finalization, because those types often need two types of clean-up. Namely: managed cleanup and unmanaged cleanup. For this reason the Dispose(bool)
method was introduced in the pattern. It prevents duplication of cleanup code (this point is missing from the other answers), because the Dispose()
method will normally cleanup both managed and unmanaged resources, while the finalizer can only cleanup unmanaged resources.
If the base class has resources that need to be cleaned up at Dispose()
time, then having a virtual Dispose
method that's overridden by an inheriting class prevents those resources from being released unless the inheriting class specifically calls the
base's Dispose
method. A better way would implement it would be to have each derived class implement IDisposable
.