Destructor
To create destructor we need to create method in a class with same name as class preceded with ~ operator.
Syntax of Destructor
class SampleA
{
public SampleA()
{
// Constructor
}
~SampleA()
{
// Destructor
}
}
Example of Destructor
In below example I created a class with one constructor and one destructor. An instance of class is created within a main function. As the instance is created within the function, it will be local to the function and its life time will be expired immediately after execution of the function was completed.
using System;
namespace ConsoleApplication3
{
class SampleA
{
// Constructor
public SampleA()
{
Console.WriteLine("An Instance Created");
}
// Destructor
~SampleA()
{
Console.WriteLine("An Instance Destroyed");
}
}
class Program
{
public static void Test()
{
SampleA T = new SampleA(); // Created instance of class
}
static void Main(string[] args)
{
Test();
GC.Collect();
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below
Output
An instance created
An instance destroyed