C# Destructor

This C# program uses a destructor. Destructors run after a class instance is removed from memory.


A destructor runs after a class becomes unreachable. It has the special "~" character in its name. The exact time it is executed is not specified. But it always runs when the class is not reachable in memory by any references.


Let's begin by looking at this Example class. It contains a constructor "Example()" and a destructor "~Example()". The destructor in a class must be prefixed with the tilde "~" character.

Here: The class Example is instantiated in the Main method. We write the method type to the console.

Output: The output shows that the constructor is run and then the destructor is run before the program exits.

C# program that uses destructor using System; class Example { public Example() { Console.WriteLine("Constructor"); } ~Example() { Console.WriteLine("Destructor"); } } class Program { static void Main() { Example x = new Example(); } } Output 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 the reference is set to null or goes out of scope). It can be run on any thread.

When you implement

IDisposable on a type, you can then use the using pattern. The using pattern gives the person writing the code a lot more control over when the instance is removed from memory and when clean up occurs.

Explanation: For this reason, the using pattern is preferable for cleaning up system resources. (Page 120.).


Destructors have advantages.

They have simpler syntax and don't require the using syntax. But they are much less useful overall. In garbage-collected languages, most actions needed at type destruction are system cleanup tasks.

And: These tasks are better suited to the explicit syntax of the using pattern.

The conclusion

is that destructors are not useful in many C# programs. In the large, complex programs that need special destruction logic, the using-dispose pattern is usually better. In simple programs, neither construct is useful.


We looked at the destructor syntax in the C# language, and compared destructors to their main competition, the using-dispose pattern. We cited the weaknesses of destructors. They are of limited utility in garbage-collected languages.

And: Destructors have less predictable behavior than the using-dispose pattern, further diminishing their usefulness.

Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen,