Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
poly
override
finalize

Override finalize in C#

Educative Answers Team
widget

Overview

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 class
class edpresso
{
  // A string variable to store URL
  string URL;

  // Constructor assigning URL
  edpresso()
  {
    this.URL = "educative.io/edpresso";
  }

  // Method to print URL
  void PrintURL()
  {
    Console.WriteLine(URL);
  }

  // Overriding Finalize the wrong way!
  protected override void Finalize()
  {
    Console.WriteLine("Finalize overridden");
  }

  static void Main() 
  {
    // your code goes here

    edpresso 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 class
class edpresso
{
  // A string variable to store URL
  string URL;

  // Constructor assigning URL
  edpresso()
  {
    this.URL = "educative.io/edpresso";
  }

  // Method to print URL
  void PrintURL()
  {
    Console.WriteLine(URL);
  }

  // Overriding Finalize the right way!
  ~edpresso()
  {
    Console.WriteLine("Finalize overridden");
  }

  static void Main() 
  {
    // your code goes here

    edpresso 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.

RELATED TAGS

c#
poly
override
finalize
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring