articles

Home / DeveloperSection / Articles / What is destructor in C# and Working?

What is destructor in C# and Working?

Sushant Mishra4016 14-Sep-2017

Destructors are used to destruct instances of classes.  In this article I will explain 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. It’s the Garbage collector (.Net Framework) who has the control over the destructor (in C#).

Syntax for destructor

  ~classname ()

        {

        }

~ (we say it tilled) 

Now are going know it characteristics one by one

Characteristics of Destructor

  1. Destructors (~) cannot be defined in Struts.
  2. Destructors (~) are only used with classes.
  3. Destructor cannot be inherited or overloaded.
  4. Destructor does not take modifiers or have parameters.
  5. It cannot be called. Destructor are called automatically.
  6. An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.
  7. We have  no control over when destructor is called because this is determined by Garbage Collector.
  8. Destructor is called when program exits.
  9. Execution of the destructor for the instance may occur at any time after the

instance becomes eligible for destruction.

Its execution order is reverse in comparison to constructor,Let us take an example

to see this

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication2
{
    classProgram
    {
        classDestructor_1
        {
     ~Destructor_1()
      {
        System.Console.WriteLine("First's destructor is called");
      }
        }
        classDestructor_2 : Destructor_1
        {
   ~Destructor_2()
     {
       System.Console.WriteLine("Second's destructor is called");
     }
        }
      classDestructor_3 : Destructor_2        {
     ~Destructor_3()
       {
         System.Console.WriteLine("Third's destructor is called");
       }
        }
        classTestDestructors        {
     staticvoid Main()
      {
       Destructor_3 t = newDestructor_3();
      }
        }
           }
}
 

output

 What is destructor in C# and Working?

Working of garbage collector

  • Main function of Garbage collector is to checks for objects/unused 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.
  • Garbage collector destroys the objects only when needed. 

Updated 07-Sep-2019

Leave Comment

Comments

Liked By