How to implement the disposable pattern in a class that inherits from another disposable class?

Posted by TheRHCP on Stack Overflow See other posts from Stack Overflow or by TheRHCP
Published on 2010-04-03T15:01:18Z Indexed on 2010/04/03 15:03 UTC
Read the original article Hit count: 156

Filed under:
|
|

Hi,

I often used the disposable pattern in simple classes that referenced small amount of resources, but I never had to implement this pattern on a class that inherits from another disposable class and I am starting to be a bit confused in how to free the whole resources.

I start with a little sample code:

public class Tracer : IDisposable
{
    bool disposed;
    FileStream fileStream;

    public Tracer()
    {
        //Some fileStream initialization
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                if (fileStream != null)
                {
                    fileStream.Dispose();
                } 
            }

            disposed = true; 
        }
    }
}

public class ServiceWrapper : Tracer
{
    bool disposed;
    ServiceHost serviceHost;

    //Some properties

    public ServiceWrapper ()
    {
        //Some serviceHost initialization
    }

    //protected override void Dispose(bool disposing)
    //{
    //    if (!disposed)
    //    {
    //        if (disposing)
    //        {
    //            if (serviceHost != null)
    //            {
    //                serviceHost.Close();
    //            } 
    //        }

    //        disposed = true;
    //    }
    //}
}

My real question is: how to implement the disposable pattern inside my ServiceWrapper class to be sure that when I will dispose an instance of it, it will dispose resources in both inherited and base class?

Thanks.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about idisposable