Destructors are the way to remove instances of classes as soon as class closed. It is very important to clean memory and remove all the instances of program. Using of destructors you can clean memory if your program is using expensive external resource as files, image etc.

Note: You should not use empty destructor in program. When you use destructor, an entry is created in Finalize queue. Therefore, when destructor is called, the garbage collector in invoked to process the queue. If you have used empty destructor, it cause unnecessary system performance issue.

When a Destructor called it automatically invokes Finalize Method. Finalize method in C# is used for cleaning memory from unused objects and instances. So, when you call destructor, it actually translates into following code.

protected override void Finalize()
{
    try
    {
        // Cleanup statements...
    }
    finally
    {
        base.Finalize();
    }
}

The programmer has no control when destructor will be executed because it is defined by garbage collector. Garbage collector automatically checks for objects that is no longer referenced or no longer being used by application. When garbage collector found such objects, it removes them automatically and free or clean  up memory.

In  C# doesn’t require explicit memory management because the .Net Framework garbage collector automatically does it for you.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Destructor_Example
{
    class first
    {
        public first()
        {
            Console.WriteLine("First Object Created. Press Enter to destroy it.");
        }
        ~first()
        {
            Console.WriteLine("Destroying First Object");            
            Console.ReadLine();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            first ft = new first()
            Console.ReadLine();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *