IDisposable Interface
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
Overview
- Enable 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
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



