What is the difference between Finalize and Dispose in C#?


Finalize

Finalize() is called by the Garbage Collector before an object that is eligible for collection is reclaimed. Garbage collector will take the responsibility to deallocate the memory for the unreferenced object. The Garbage Collector calls this method at some point after there are no longer valid references to that object in memory.

The framework does not guarantee that when this will happen, we can force for Garbage Collection but it will hurt performance of a program. Finalize() belongs to the Object class and it will be called by the runtime.

Example

using System;
namespace DemoApplication{
   public class Demo{
      ~Demo(){
         Console.WriteLine("Finalize called");
      }
   }
}

Dispose

There are some resources like windows handles, database connections, network connections, files, etc. which cannot be collected by the Garbage Collector. If we want to explicitly release some specific objects then this is the best to implement IDisposable and override the Dispose() method of IDisposable interface.

The Dispose() method is not called automatically and we must explicitly call it from a client application when an object is no longer needed. Dispose() can be called even if other references to the object are alive.

Example

using System;
namespace DemoApplication{
   public class Demo : IDisposable{
      private bool disposed = false;
      public void Dispose(){
         Dispose(true);
         GC.SuppressFinalize(this);
      }
      protected virtual void Dispose(bool disposing){
         if (!disposed){
            if (disposing){
               //clean up managed objects
            }
            //clean up unmanaged objects
            disposed = true;
         }
      }
   }
}

Microsoft recommends that we implement both Dispose and Finalize when working with unmanaged resources. The Finalize implementation would run and the resources would still be released when the object is garbage collected even if a developer neglected to call the Dispose method explicitly.

Updated on: 04-Aug-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements