A destructor is special type of method of a class and it is used in a class to destroy the object that are not longer used in program it also destroy the instance of class. In C#, destructor is invoke automatically whenever the class instance become unreachable.
Property of a Destructor:
There are following some property of a destructor in C# are as,]
1- A destructor can always used in a class.
2- A destructor is represented with tiled(~) operator.
3- A destructor will not any parameter and can not used any access modifier with destructor.
4- Destructor is automatically invoked by garbage collector when the class object are no longer used in the program.
Syntax –
Class Demo
{
~Demo()
{ // code of destructor
}
}
Example-
using System;
namespace MindStick
{
class Demo
{
public Demo()
{
Console.WriteLine('An Instance is Created');
}
// Destructor
~Demo()
{
Console.WriteLine('An Instance is destroyed');
}
}
class SampleProgram
{
static void Main(string[] args)
{
Details();
GC.Collect();
Console.ReadLine();
}
public static void Details()
{
// Created instance of the class
Demo user = new Demo();
}
}
}
Output:
An Instance is Created
An Instance is destroyed
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Destructor in C#:
A destructor is special type of method of a class and it is used in a class to destroy the object that are not longer used in program it also destroy the instance of class. In C#, destructor is invoke automatically whenever the class instance become unreachable.
Property of a Destructor:
There are following some property of a destructor in C# are as,]
1- A destructor can always used in a class.
2- A destructor is represented with tiled(~) operator.
3- A destructor will not any parameter and can not used any access modifier with destructor.
4- Destructor is automatically invoked by garbage collector when the class object are no longer used in the program.
Syntax –
Example-
Output: