In this article we are going to discuss about destructor with examples in C#.
A destructor in C# is a special method inside the class used to destroy instances of that class when they are no longer needed. Destructors are particularly useful for releasing unmanaged resources like file handles, database connections, or unmanaged memory that the .NET garbage collector does not handle automatically.
The Destructor is called implicitly by the .NET Framework’s Garbage collector.
The syntax for defining a destructor is similar to that of a constructor but
with a tilde (~
) before the class name.
class MyClass
{
// Destructor
~MyClass()
{
// Cleanup code
}
}
When to Use Destructors