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.
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
ConstructorDestructor
Anonymous User
14-May-2019Thanks for the informative post.
Sushant Mishra
20-Jun-2017I always seek to read your articles.