Home
C#
Destructor
Updated Aug 10, 2022
Dot Net Perls
Destructor. In the C# language a destructor runs after a class becomes unreachable. It has the special "~" character in its name.
Destructor info. 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.
class
Unreachable
An example. Let us begin by looking at this Example class. It contains a constructor "Example()" and also a destructor "~Example()".
Constructor
Here The class Example is instantiated in the Main method. We write the method type to the console.
Result The output shows that the constructor is run and then the destructor is run before the program exits.
Console.WriteLine
using System; class Example { public Example() { Console.WriteLine("Constructor"); } ~Example() { Console.WriteLine("Destructor"); } } class Program { static void Main() { Example x = new Example(); } }
Constructor Destructor
Discussion. 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).
Info When you implement IDisposable, you can use the "using" pattern. This lets us know exactly when clean up must occur.
So For this reason, the using pattern is preferable for cleaning up system resources (page 120).
using
Destructors versus IDisposable. Destructors have simpler syntax and don't require the using syntax. Most actions needed at type destruction are system cleanup tasks.
And These tasks are better suited to the explicit syntax of the using pattern.
Thus In complex programs that need special destruction logic, the using-dispose pattern is usually better.
A summary. We examined destructor syntax, and compared destructors to the using-dispose pattern. Destructors are rarely needed in C# programs.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 10, 2022 (image).
Home
Changes
© 2007-2025 Sam Allen