Search code examples
c#.netinheritancedisposeidisposable

Disposing base class before inherited class


I have two classes:

public abstract class UnitOfWorkBase: IDisposable { }
public sealed class UnitOfWorkSql: UnitOfWorkBase { }

The Dispose method of the derived class normally looks like this:

protected override void Dispose (bool disposing)
{
    if (!this.Disposed)
    {
        if (disposing)
        {
            // Managed.
        }

        // Unmanaged.

        this.Disposed = true;
    }

    base.Dispose(disposing);
}

I've always seen the call to base.Dispose(disposing) at the end of the method. However, in a recent scenario, there is a need to dispose objects of the base class before objects in the derived class as follows:

protected override void Dispose (bool disposing)
{
    base.Dispose(disposing);

    if (!this.Disposed)
    {
        if (disposing)
        {
            // Managed.
        }

        // Unmanaged.

        this.Disposed = true;
    }
}

I'm not sure if this is considered bad practice. Is there anything to watch out for?


Solution

  • I think you should break the usual pattern here. Instead of:

    class BaseClass
    {
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                //dispose my resources
            }
        }
    }
    

    Write something like:

    class BaseClass
    {
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                //dispose my resources
                DisposeManagedOverride();
            }
    
            CloseUnmanagedOverride();
        }
    
        protected virtual void DisposeManagedOverride() {}
    
        protected virtual void CloseUnmanagedOverride() {}
    }
    

    This way you will ensure the proper order of the resources release.