Muhammad Imran Ansari
What is the difference between Finalize() and Dispose() methods?

What is the difference between Finalize() and Dispose() methods?

By Muhammad Imran Ansari in .NET on Oct 24 2022
  • Brahma Prakash Shukla
    Oct, 2022 29

    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 objectsdisposed = 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.

    • 2
  • Pankaj Patel
    Nov, 2022 15

    Hi Muhammad Imran Ansari,

    The main difference between dispose() and finalize() is that:

    1. dispose() has to be explicitly invoked by the user.
    2. finalize() is invoked by the garbage collector, just before the object is destroyed.

    For more details:

    Difference Between dispose() and finalize() in C#
    https://techdifferences.com/difference-between-dispose-and-finalize-in-c-sharp.html

    Hope, this will help you

    • 1
  • Rajeev Kumar
    Jun, 2023 29

    It belongs to IDisposable interface and It belongs to Object class.dispose() must be explicitly invoked by the programmer. In contrast, finalize() method is invoked by the GC before the object is destroyed

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS