How-to-simply...

Implement IDisposable and Dispose pattern in C#

  • 1 In order to use the IDisposable interface, you would declare a class like this:
    public class MyClass : IDisposable
    {
    public void Dispose()
    {
    // Perform any object clean up here.
    // If you are inheriting from another class that
    // also implements IDisposable, don't forget to
    // call base.Dispose() as well.
    }
    }
  • 2 In every case where a type owns resources, or owns types that own resources, you should give users the ability to explicitly release those resources by providing a public Dispose method (Explicit Cleanup). This alleviates some of the reliance on the GC, and provides users a way to deterministically reclaim resources.
  • N public class MyDisposable : IDisposable
    {
      bool isDisposed;
      public void Dispose()
      {
        Dispose(true);
        GC.SuppressFinalize(this);
      }
      ~MyDisposable() => Dispose(false);
      private void Dispose(bool disposing)
      {
         if (!isDisposed) {
          if (disposing) {
            // DISPOSE ALL MANAGED RESOURCES HERE!
          }
          // CLEANUP ALL UNMANAGED RESOURCES HERE!
          isDisposed = true;
        }
      }
    }

References