In the C# language a destructor runs after a class
becomes unreachable. It has the special "~" character in its name.
The exact time a destructor is executed is not specified. But it always runs when the class
is not reachable in memory by any references.
Let us begin by looking at this Example class
. It contains a constructor "Example()
" and also a destructor "~Example()
".
class
Example is instantiated in the Main
method. We write the method type to the console.using System; class Example { public Example() { Console.WriteLine("Constructor"); } ~Example() { Console.WriteLine("Destructor"); } } class Program { static void Main() { Example x = new Example(); } }Constructor Destructor
We next reference the C# specification. The destructor can be run at any time after the class
instance becomes unreachable (such as when it goes out of scope).
IDisposable
, you can use the "using" pattern. This lets us know exactly when clean up must occur.IDisposable
Destructors have simpler syntax and don't require the using syntax. Most actions needed at type destruction are system cleanup tasks.
using
-dispose pattern is usually better.We examined destructor syntax, and compared destructors to the using
-dispose pattern. Destructors are rarely needed in C# programs.