March 27, 2006

Dispose Pattern

Explains how to implement IEnumerator and Contains basic IDispose pattern and more Msdn Guidelines on Implementing IDisposable and Equals Operators

Basic IDisposable Implementation
// Design pattern for a base class.
public class Base: IDisposable
{

#region Dispose Implementation

   // Use C# destructor syntax for finalization code.
   ~Base()
   {
      Debug.Assert(false, "This object was not disposed of");
      // Simply call Dispose(false).
      Dispose (false);
   }

   private bool _isDisposed = false;

   //Implement IDisposable.
   public void Dispose() 
   {
      Dispose(true);
      GC.SuppressFinalize(this); 
   }

   protected virtual void Dispose(bool disposing) 
   {
      if (_isDisposed)
        return;

      if (disposing) 
      {
         // Free other state (managed objects).
      }
      // Free your own state (unmanaged objects).
      // Set large fields to null.
      _isDisposed = true;
   }

#endregion Dispose Implementation


...
}
   
// Design pattern for a derived class.
public class Derived: Base
{  

#region Dispose Implementation 

   private bool _isDerivedDisposed = false;

   protected override void Dispose(bool disposing) 
   {
      if (disposing) 
      {
         // Release managed resources.
      }
      // Release unmanaged resources.
      // Set large fields to null.
      
      // Call Dispose on your base class.
      base.Dispose(disposing);

      _isDerivedDisposed = true;
   }
   
   // The derived class does not have a Finalize method
   // or a Dispose method with parameters because it inherits
   // them from the base class.

#endregion Dispose Implementation

}

No comments: