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()
        //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.
            // Simply call Dispose(false).
#endregion// IDisposable Methods

For more information you can see the article on MSDN.

About SheldonS

Web developer for over 15 years mainly with Microsoft technologies from classic ASP to .NET 4. Husband, father, and aspiring amateur photographer.

Posted on October 12, 2011, in C#. Bookmark the permalink. Leave a comment.

Leave a Reply

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

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

Google photo

You are commenting using your Google 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: