Destructors in C#

As its name suggest, destructors are used to destroy the object. It internally called the finalize method. Its name is same as class name and appended with special symbol called as tilde (∼). Destructors cannot be defined in structs.

Key things about static constructor are:

  • You can create only one destructor in a class.
  • Destructors cannot be inherited.
  • It does not take any parameter.
  • Destructors cannot be called explicitly. They are invoked automatically.
  • A destructor does not take modifiers.

Example

using System;
namespace ConsoleApplication1
{
    class BaseClass
    {
        public BaseClass()
        {
            Console.WriteLine("Base Class constructor is called");
        }
       ∼ BaseClass()
        {
            Console.WriteLine("Destroying BaseClass");
        }
    }
    class DerivedClass : BaseClass
    {
        public DerivedClass()
        {
            Console.WriteLine("Derived Class constructor is called");
        }
        ∼ DerivedClass()
        {
            Console.WriteLine("Destroying DerivedClass");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass obj = new DerivedClass();
            Console.WriteLine("Object Created ");     
            Console.ReadLine();           
        }
    }
}


Note: Destructors are called when the program exits.