Click Here

Saturday, 14 May 2016

Destructor

Destructor A destructor runs after a class becomes unreachable. It has the special "~" character in its name. The exact ti... thumbnail 1 summary
Destructor


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.

Example. 

 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.

The class Example

is instantiated in the Main method. We write the method type to the console. The output, below, 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


No comments

Post a Comment