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
~ (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
- 3-Destructor cannot be inherited or
- 4-Destructor does not take modifiers or
- 5-It cannot be called. Destructor are called
- 6-An instance becomes eligible for
destruction when it is no longer possible for any code to use the
- 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
Its execution order is
reverse in comparison to constructor,Let us take an example
to see this
System.Console.WriteLine("First's destructor is called");
class Destructor_2 : Destructor_1
System.Console.WriteLine("Second's destructor is called");
class Destructor_3 : Destructor_2
System.Console.WriteLine("Third's destructor is called");
static void Main()
Destructor_3 t = new Destructor_3();
Working of garbage
- 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.