Home > C# > Implementing IDisposable

Implementing IDisposable

Here is something I tend to forget from time to time.  How to impliment IDisposable for a class.  While there are many places to find this, I tend to go to my blog first, because usually I will put something in here for what I need.

When declaring you class you need to have it inherit the IDisposable class.

public class MyClass : IDisposable

After that, somewhere in your class you need to implement the methods.

#region IDisposable Methods
        //Implement IDisposable.
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        //This is where you will do the cleaning
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Free other state (managed objects).
            }
            // Free your own state (unmanaged objects).
            // Set large fields to null.
        }

        //MSDN says you can leave the finalizer out if
        //the class does not own unmanaged resources.
        ~MyClass()
        {
            // Simply call Dispose(false).
            Dispose(false);
        }
#endregion// IDisposable Methods

For more information you can see the article on MSDN.

Advertisement
Categories: C#
  1. No comments yet.
  1. No trackbacks yet.

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 36 other followers