Users Pricing

blog

Home Blogs Destructor in C# – MindStick

Destructor in C#

Amit Singh 4291 06 Nov 2010 Updated 18 Sep 2014

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

Amit Singh

Other


2 Comments


Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md