blog

Home / DeveloperSection / Blogs / Destructor in C#

Destructor in C#

Amit Singh 3735 06-Nov-2010

A destructor is a function with the same name as the name of a class but starting with the character ~. A constructor gets called at birth whereas a destructor gets called at death.

In C# we cannot decide when the destructor gets called. This decision to call the destructor is made by a program within C# called the garbage collector.
The concept first gained currency with the advent of Java. In Java and C# we cannot remove our objects from memory. Thus it is for the garbage collector to decide when to call the destructor.
For Example:

public class Sample
{
public static void Main()
{
aa a = new aa();
}
}
public class aa
{
public aa()
{
System.Console.WriteLine("Constructor ");
}
~aa()
{
System.Console.WriteLine("Destructor");
}
}
Output
Constructor
Destructor

c# c# 
Updated 18-Sep-2014

Leave Comment

Comments

Liked By