Destructors

Destructors are the opposite of constructors. Destructors are also special methods that are called when the object is being destroyed. Objects use the memory of your computer and if they are not removed from the memory, you will suffer a memory leak. You can use the destructor as a clean up tool or to remove any resources that aren’t needed by the program.

The .NET Framework offers automatic garbage collection so you don’t need to manually remove the objects (or dispose them) from the memory. There are times where the garbage collector can’t do its job well. For example, when creating a connection to a database, or when opening a stream for reading a text file. With the use of destructors, you define the code that will be executed when an object is destroyed. Usually, an object is destroyed when it leaves a scope. The syntax of a destructor is a little different than the constructor.

~ClassName()
{
   code to execute;
}

Like a constructor, the destructor should also match the name of the class. Notice that we precede the name with a tilde (~) which is found below the escape key on your keyboard. The destructor cannot have access specifiers such as public. The program below shows the order by which the destructor and constructor are called.

 

using System;
 
namespace DestructorsDemo
{
    public class Test
    {
        public Test()
        {
            Console.WriteLine("Constructor was called.");
        }
        ~Test()
        {
            Console.WriteLine("Destructor was called.");
        }
    }
 
    public class Program
    {
        public static void Main()
        {
            Test x1 = new Test();
        }
    }
}

Example 1 – Creating a Destructor

Constructor was called.
Destructor was called.

We defined both a constructor and a destructor for class Test. We then created an instance of it inside the Main() method. When we created the instance, the constructor was called and the proper message was displayed. When we left the  Main() method, the object was destroyed and the destructor was called. The .NET Framework actually interprets a destructor as a method that overrides  the Finalize() method of the System.Object.