1

In C# I learned I can create a class destructor as follows:

public class MyClass
{
    ~MyClass()
    {

    }
}

My question is when and in what situation should I be using a destructor in C#, if ever?

Is there one common use case I should watch out for?

Richard Tozier
  • 164
  • 1
  • 5
  • Just for reference http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx – Tony Oct 09 '13 at 15:11
  • Probably never. Use IDisposable if you want to manage resources. –  Oct 09 '13 at 15:12
  • The "destructor" is syntactic sugar for the override of `Finalize`. Use that to close/clean resources manually, for example a closing a stream or stuff like that. – Pierre-Luc Pineault Oct 09 '13 at 15:12

1 Answers1

1

The programmer has no control on when the destructor is going to be executed because this is determined by the Garbage Collector. The garbage collector checks for objects that are no longer being used by the application. It considers these objects eligible for destruction and reclaims their memory. Destructors are also called when the program exits. When a destructor executes what is happening behind the scenes is that the destructor implicitly calls the Object.Finalize method on the object's base class. destructor code is implicitly translated to something like this :

protected override void Finalize()
{
   try
   {
      // Cleaning up .
   }
   finally
   {
      base.Finalize();
   }
}
super
  • 2,288
  • 2
  • 21
  • 23