Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a destructor [duplicate]

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.

like image 739
Sanjiv Avatar asked Oct 15 '25 01:10

Sanjiv


1 Answers

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.

like image 153
areller Avatar answered Oct 17 '25 15:10

areller