Destructors in C#

C# does not feature destructors, at least not in the traditional way or in the way its ancestor (C++) did. The destructor is generally called when an object is destroyed but this is not the case with C#. The destructor of C#, instead, is called by the Garbage Collector, and the garbage collector performs a clean up only at regular interval or when the memory state requires it (in case the memory is full).

However, the syntax for a destructor remains the same as in C++. Example 4 shows a code snippet, which declares a destructor for the semester class.

Example 4:

...
~semester()
{
   // Destructor Implementation
}
...

Before we proceed with the discussion on destructors, it is essential to understand how the garbage collector works.

1.   The Garbage Collector of C#

The Garbage collector is responsible for freeing up memory by destroying objects that are no longer referenced. The working of the garbage collector is as explained.

  • When an object, that has a destructor defined, is allocated in the memory, the runtime adds this object to a list of objects that require destruction (or finalization). The runtime refers to the destructor as a finalizer, it is only C# which calls it a destructor.
  • The garbage collector starts on its rounds and checks if there are objects that have no references.
  • If an object is found and if the name of the object does not appear in the finalizer list then it is cleared up right then.
  • If the name of the object appears on the list of objects that require finalization, it is marked as “ready for finalize”.
  • When the garbage collection is complete then the finalizer thread is called which goes about calling the finalizer methods of all objects which have been marked as “ready for finalize”.
  • After the finalization of an object has occurred it is removed from the list of objects, which require finalization.
  • Since the object is no longer on the finalizer list nor is it referenced, it gets cleared up when the garbage collection takes place the next time!

The garbage collector may seem exciting but it has its own drawbacks, which are discussed below along with the way they can be dealt with.

  • Objects with destructors take up more resources as they stay for a longer period of time in memory even when they are not required!
  • Finalization takes place as a separate thread again eating into the resources.

Hence it is recommended to write Destructors only where absolutely necessary.

Remember destructors are not called when a program exits! Though this cab be achieved but is discouraged as a good programming practice.

Leave a comment