C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
ConsoleC# 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
Explanation: For this reason, the using pattern is preferable for cleaning up system resources (page 120).
UsingAnd: These tasks are better suited to the explicit syntax of the using pattern.
And: Destructors have less predictable behavior than the using-dispose pattern, further diminishing their usefulness.