Implementing IDisposable on a subclass when the parent also implements IDisposable
- by Tanzelax
I have a parent and child class that both need to implement IDisposable. Where should virtual (and base.Dispose()?) calls come into play? When I just override the Dispose(bool disposing) call, it feels really strange stating that I implement IDisposable without having an explicit Dispose() function (just utilizing the inherited one), but having everything else.
What I had been doing (trivialized quite a bit):
internal class FooBase : IDisposable
{
Socket baseSocket;
private void SendNormalShutdown() { }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
SendNormalShutdown();
}
baseSocket.Close();
}
}
~FooBase()
{
Dispose(false);
}
}
internal class Foo : FooBase, IDisposable
{
Socket extraSocket;
private bool _disposed = false;
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
extraSocket.Close();
}
base.Dispose(disposing);
}
~Foo()
{
Dispose(false);
}
}