Reader Level:
ARTICLE

Destructor in C#

Posted by Deepak Dwij Articles | C# Language November 15, 2011
Destructors are used to destruct instances of classes. In this article you will understand how different a C# destructor is when compared to a C++ destructor.
  • 1
  • 0
  • 7051

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

  • Destructors (~) cannot be defined in Structs.

  • Destructors (~) are only used with classes.

  • Destructor cannot be inherited or overloaded.

  • Destructor does not take modifiers or have parameters.

  • Destructor cannot be called. They are invoked automatically.

  • An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.

  • The Programmer has no control over when destructor is called because this is determined by Garbage Collector.

  • Destructor is called when program exits.

  • Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.

  • Destructor implicitly calls Finalize on the base class of object.

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

  • Garbage collector  checks for objects that are no longer being used by application, if it treated an object eligible for destruction, it calls the destruction and reclaims the memory used to store  the object.

  • GC keeps tracks of all the objects and ensures that each object gets destroyed once.

  • GC ensures that objects, which are being referenced, are not destroyed.

  • GC destroys the objects only when necessary. Some situations of necessity are memory is exhausted or user explicitly calls System.GC.Collect() method.

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) 

COMMENT USING

Trending up