The following code explains the Destructors in C#.
Destructors begin with ~ symbol followed by class name.
There should not be any parameters in the brackets.
Syntax:
class A
{
~A()
{
code;
}
}
Example:
using System;
using System.Text;
namespace forgetCode
{
class A
{
~A()
{
Console.WriteLine("Destruct instance of A");
}
}
class B
{
object Ref;
public B(object o)
{
Ref = o;
}
~B()
{
Console.WriteLine("Destruct instance of B");
}
}
class program
{
public static void Main()
{
B b = new B(new A());
b = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
Output:
Destruct instance of B
Destruct instance of A
or
Destruct instance of A
Destruct instance of B
The output could be either because the language imposes no constraints on the order in which objects are garbage collected.