Home
C#
Destructor
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 10, 2022 (image).
Home
Changes
© 2007-2024 Sam Allen.