Differences between the Dispose() and Finalize() methods in C# - ablealias/asp.net GitHub Wiki

CLR (Common Language Runtime) uses the Dispose and Finalize methods to perform garbage collection of run-time objects of .NET applications.

The Finalize method is called automatically by the runtime. CLR has a garbage collector (GC), which periodically checks for objects in heap that are no longer referenced by any object or program. It calls the Finalize method to free the memory used by such objects.

The Dispose method is called by the programmer. Dispose is another method to release the memory which used by an object. The Dispose method needs to be explicitly called in the code to release an object from the heap. The Disposes method can be invoked by the classes that implement the IDisposable interface.

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

class BaseClass : IDisposable
{
   // Flag: Has Dispose already been called?
   bool disposed = false;
   // Instantiate a SafeHandle instance.
   SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);

   // Public implementation of Dispose pattern callable by consumers.
   public void Dispose()
   { 
      Dispose(true);
      GC.SuppressFinalize(this);           
   }

   // Protected implementation of Dispose pattern.
   protected virtual void Dispose(bool disposing)
   {
      if (disposed)
         return; 

      if (disposing) {
         handle.Dispose();
         // Free any other managed objects here.
         //
      }

      // Free any unmanaged objects here.
      //
      disposed = true;
   }
}