C# Language In an inherited class with managed resources


Example

It's fairly common that you may create a class that implements IDisposable, and then derive classes that also contain managed resources. It is recommendeded to mark the Dispose method with the virtual keyword so that clients have the ability to cleanup any resources they may own.

public class Parent : IDisposable
{
    private ManagedResource parentManagedResource = new ManagedResource();

    public virtual void Dispose()
    {
        if (parentManagedResource != null)
        {
            parentManagedResource.Dispose();
        }
    }
}

public class Child : Parent
{
    private ManagedResource childManagedResource = new ManagedResource();

    public override void Dispose()
    {
        if (childManagedResource != null)
        {
            childManagedResource.Dispose();
        }
        //clean up the parent's resources
        base.Dispose();
    }
}