Introduction

Destructors are used to destruct instances of classes. In this article, you will understand how different C# destructors are when compared to C++ destructors.

In C# you can never call them, the reason is one cannot destroy an object. So who has the control over the destructor (in C#)? it's the .NET frameworks Garbage Collector (GC).

Syntax of Destructor(~)

~ ClassName()

using System;
namespace destructorex
{
    class Program
    {
        ~Program() // destructor define
        {
           // clean up statement
        }
    }
}

Characteristics of Destructor

Example

The above given code is implicitly translated to the following code:

protected override void Finalize()
{
    try
    {
        // to clean conditions
    }
    finally
    {
        base.Finalize();
    }
}

Explanation of code: Finalize() is called recursively for all instances in the inheritance chain, from most derived to least derived.

Garbage collector

Note : Execution order: Base constructor is getting called first. In general, destructors are called in the reverse order of the constructor calls.

Program of Execution order

class First
{
    ~First()
    {
        System.Console.WriteLine("First's destructor is called");
    }
}
class Second : First
{
    ~Second()
    {
        System.Console.WriteLine("Second's destructor is called");
    }
}
class Third : Second
{
    ~Third()
    {
        System.Console.WriteLine("Third's destructor is called");
    }
}
class TestDestructors
{
    static void Main()
    {
        Third t = new Third();
    }
}

Output

dee.gif

ILDASM command

2.gif

Note: Execution order base constructor is getting called first. In general, destructors are called in the reverse order of the constructor calls.

Some Useful Points

  1. When your application encapsulates unmanaged resources such as:
    • Windows
    • Files
    • Network connections

    you should use destructors to free those resources.

  2. When an object is eligible for destruction, the garbage collector runs the Finalize () method of that object.
  3. Empty destructors should not be used
    Reason - When a class contains a destructor, an entry is created in the finalize queue. if the destructor is empty, this just causes a needless loss of performance.
  4. Explicit release of resources
    Suppose an application uses a costly external resources, then a way to explicitly release the resource before the garbage collector frees the object.
    IDisposable Interface - Defines a method to release allocated resources.
    Namespace: System
    Assembly: mscorlib (in mscorlib.dll)