MS advices that base class should provide protected virtual void Dispose(bool disposing)
in the derived classes. I have an existing class written much earlier which does not provide such function. By knowing the fact base class is Disposable, can we simply use the following in any derived class?
class Base : IDisposable
{
//This somehow disposes it's resources
}
class Derived : Base
{
bool disposed;
private void PrivateDispose(bool disposing)
{
if (disposed) return;
if (disposing) {
// Cleanup managed resources
// ...
// Simply dispose base class
base.Dispose();
}
// Cleanup unmanged resources if any
// ...
disposed = true;
}
public void Dispose()
{
PrivateDispose(true);
GC.SuppressFinalize(this);
}
// Only provide Finalizer if we have unmanaged resources
~Derived()
{
PrivateDispose(false);
}
}
Yes, you can. The reason MS recommends this is to make it easy for any implementers of derived types to override the existing Dispose(bool disposing)
method, since the public void Dispose()
implemented by the IDisposable
interface isn't virtual
.
Note that you should use this pattern. Change:
private void PrivateDispose(bool disposing)
To:
protected virtual void Dispose(bool disposing)
So if anyone potentially needs to extend your class, he can simply override your method.
In general, here are some more guidelines for implementing IDisposable
:
Dispose should meet the following conditions:
1) Be safely callable multiple times
2) Release any resources associated with the instance
3) Call the base class's Dispose method, if necessary
4) Suppress finalization of this class to help the GC by reducing the number of objects on the finalization queue.
5) Dispose shouldn't generally throw exceptions, except for very serious errors that are particularly unexpected (ie, OutOfMemoryException). Ideally, nothing should go wrong with your object by calling Dispose.