I know destructors are called by the garbage collector (GC) when objects are no longer used.
But how can I call the destructor through C# code?
If possible please give some basic example for understanding.
You don't call the destructor in .NET. The managed heap is handled by the CLR and the CLR only.
You can, however, define a destructor to a class. The destructor would be called once the object gets collected by the GC.
class Foo
{
public Foo()
{
Console.WriteLine("Constructed");
}
~Foo()
{
Console.WriteLine("Destructed");
}
}
Take notice that the destructor doesn't (and can't) have a public modifier in-front of it. It's sort of a hint that you can't explicitly call the destructor of an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With