How To Dispose

Published on Saturday, December 30, 2023

How To: Dispose

Classes that descend from a component that already implements IDisposable don�t have to explicitly declare that they do. Otherwise, you should indicate that your class implements IDisposable.

There are other, shorter ways to implement IDisposable that are also correct in some circumstances, but I like to use this way consistently.

You always need a _isDisposed field.

private bool _isDisposed;

When you are not subclassing a class that implements IDisposable:

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

protected virtual void Dispose(bool disposing)
{
  if (!_isDisposed)
  {
    if (disposing)
    {
      // Cleanup goes here
    }
  _isDisposed = true;
  }
}

When you _are _subclassing a class that does implement IDisposable:

protected override void Dispose(bool disposing)
{
  if (!_isDisposed)
  {
    if (disposing)
    {
      // Cleanup goes here
    }

  _isDisposed = true;
  }

  base.Dispose(disposing);
}