Implementing IDisposable on a subclass when the parent also implements IDisposable

Posted by Tanzelax on Stack Overflow See other posts from Stack Overflow or by Tanzelax
Published on 2010-03-22T22:50:00Z Indexed on 2010/03/22 23:01 UTC
Read the original article Hit count: 400

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);
    }

}

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET