#430 – A Dispose Pattern Example

If you want to control when an object’s unmanaged resources are released, you can follow the dispose pattern, implementing a Dispose method.

Here’s a complete example.  We create a method to release resources that is called either when a client invokes Dispose directly or when the CLR is finalizing the object.

    public class Dog : IDisposable
        // Prevent dispose from happening more than once
        private bool disposed = false;

        // IDisposable.Dispose
        public void Dispose()
            // Explicitly dispose of resources

            // Tell GC not to finalize us--we've already done it manually

        // Function called via Dispose method or via Finalizer
        protected virtual void DoDispose(bool explicitDispose)
            if (!disposed)
                // Free some resources only when invoking via Dispose
                if (explicitDispose)
                    FreeManagedResources();   // Define this method

                // Free unmanaged resources here--whether via Dispose
                //   or via finalizer

                disposed = true;

        // Finalizer

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #430 – A Dispose Pattern Example

  1. Pingback: #737 – When to Implement a Finalizer « 2,000 Things You Should Know About C#

  2. chaitanya says:

    A quick question, why is the method DoDispose protected and virtual? Could you please explain the specific reason?


    • Sean says:

      It’s protected so that a child class can call it, if desired. It’s virtual so that a child class can override it as a virtual method. Being virtual, the DoDispose logic in the parent class will then correctly invoke the method in the child class.

  3. Pingback: Object Disposal and BackgroundWorker Object in .NET | Sean's Stuff

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: