I have a parent and child class that both need to implement IDisposable
. Where should virtual
(and base.Dispose()
?) calls come into p
Why complicate things when you don't need to?
Since you don't encapsulate any unmanaged resources, you don't need all that mucking about with finalization. And, your classes are internal, which suggests that you control the inheritance hierarchy within your own assembly.
So, the straighforward approach would be:
internal class FooBase : IDisposable
{
Socket baseSocket;
private void SendNormalShutdown()
{
// ...
}
private bool _disposed = false;
public virtual void Dispose()
{
if (!_disposed)
{
SendNormalShutdown();
baseSocket.Close();
_disposed = true;
}
}
}
internal class Foo : FooBase
{
Socket extraSocket;
private bool _disposed = false;
public override void Dispose()
{
if (!_disposed)
{
extraSocket.Close();
_disposed = true;
}
base.Dispose();
}
}
Even when you do have unmanaged resources, I'd say you're much better off encapsulating them in their own disposable class and using them like you'd use any other disposable; as straighforward as the code above.