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#