Overview
- Enables assemblies that create an instance of your class to free up any resources the instance has consumed.
- Only implement IDisposable when one of your members implements it, or when you use native resources.
Good practice
- Implement a virtual Dispose(bool) in your base class which combines disposing native and managed resources.
- Dispose() will call Dispose(true), while the finalizer will call Dispose(false).
- A Dispose method should call the GC.SuppressFinalize method for the object it is disposing.
Examples
Basic IDisposable Implementation
public class DisposableClass : IDisposable
{
private bool _disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// Note that Dispose() is not thread-safe in this form!
// If thread-safety is required, you need to implement this.
if (!_disposed)
{
if (disposing)
{
// Dispose managed resources.
}
// Release unmanaged resources.
}
_disposed = true;
}
~DisposableClass()
{
Dispose(false);
}
public void SomeMethod()
{
if (this._disposed) { throw new ObjectDisposedException(this.GetType().Name); }
}
}
public class DisposableSubClass : DisposableClass
{
private bool _disposed = false;
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
try
{
if (disposing)
{
// Release the managed resources you added in
// this derived class here.
}
// Release the native unmanaged resources you added
// in this derived class here.
_disposed = true;
}
finally
{
// Call Dispose on your base class.
base.Dispose(disposing);
}
}
}
}
using (DisposableClass c = new DisposableClass())
{
c.SomeMethod();
}
You May Also Like

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.




