1

I know destructor are called by Garbage Collector when object is no longer used. But I want to know

How to call destructor through c# code?

If possible please give some basic example for understanding.

Sanjiv
  • 980
  • 2
  • 11
  • 29
  • Why do you think you need to call the destructor? – D Stanley Jan 30 '17 at 18:30
  • 3
    You almost certainly don't need to *have* a finalizer (C# doesn't have destructors, only finalizers), let alone manually calling it. You almost certainly should only have a `Dispose` method, and you *should* be manually calling *that*. – Servy Jan 30 '17 at 18:34
  • 1
    The other option is to wrap it in a `using` statement so it should auto-dispose – BenKoshy Mar 27 '18 at 01:43

2 Answers2

18

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 an hint that you can't explicitly call the destructor of an object.

areller
  • 4,800
  • 9
  • 29
  • 57
-2

You can look at the Destructor Microsoft docs.

You need to declare a function with same name as the class name but with a leading "~" sign.

LoukMouk
  • 503
  • 9
  • 29
Anubhav Dhawan
  • 1,431
  • 6
  • 19
  • 35