In C#, the Garbage Collector takes care of memory management. However, in doing so, it only collects the managed objects, unmanaged objects stay in memory occupying space.
If you are writing a memory sensitive code and want to release unmanaged objects, then you can do so by overriding the Object.Finalize
method.
If you override finalize with the keyword override, it will throw an error:
using System;// A demo classclass edpresso{// A string variable to store URLstring URL;// Constructor assigning URLedpresso(){this.URL = "educative.io/edpresso";}// Method to print URLvoid PrintURL(){Console.WriteLine(URL);}// Overriding Finalize the wrong way!protected override void Finalize(){Console.WriteLine("Finalize overridden");}static void Main(){// your code goes hereedpresso shot = new edpresso();Console.WriteLine("visit:");shot.PrintURL();}}
Instead, as the error suggests, you need to use destructor syntax to override the finalize method:
~<classname>(){
}
using System;// A demo classclass edpresso{// A string variable to store URLstring URL;// Constructor assigning URLedpresso(){this.URL = "educative.io/edpresso";}// Method to print URLvoid PrintURL(){Console.WriteLine(URL);}// Overriding Finalize the right way!~edpresso(){Console.WriteLine("Finalize overridden");}static void Main(){// your code goes hereedpresso shot = new edpresso();Console.WriteLine("visit:");shot.PrintURL();}}
When you override finalize using a destructor, the Garbage Collector adds each instance of the class to a finalization queue. When the reference to this object reaches zero and it becomes inaccessible, the Garbage Collector calls the finalize method and cleans the memory where this object exists.
You can forcefully stop Garbage Collector to invoke the finalize method by calling the GD.SuppressFinalize
method.
Free Resources