Start C# here

Study C#.. Go ahead ! !

Saturday, June 13, 2009

Destructor in C#

C# Destructors are used to destroy an object of a Class. Destructors are automatically invoked when the Scope of the Object goes out. We represent a Destructor with a tilde(~) symbol. Destructor will also be having the Same name of the class.
If there is a class with the name "Hello" we can represent its destructor as
~Hello()

Destructors cannot be overloaded, Inhertied or have Modifiers defined to it.
we can see a Simple program..

-------------------------------------------------
using System;

namespace Destructorss
{
class One
{
//Constructor
public One()
{
Console.WriteLine("First Constructor Called");
}

//Destructor
~One()
{
Console.WriteLine("First destructor is called.");
}
}

class Two : One
{
//Constructor
public Two()
{
Console.WriteLine("Second Constructor Called");
}
//Destructor
~Two()
{
Console.WriteLine("Second destructor is called.");
}
}

class Three : Two
{
//Constructor
public Three()
{
Console.WriteLine("Third Constructor Called");
}
//Destructor
~Three()
{
Console.WriteLine("Third destructor is called.");
}
}

class MyDestructor
{
static void Main()
{
Three t = new Three();
}

}
}

/*The result of this Program will be:-
First Constructor Called
Second Constructor Called
Third Constructor Called

Third destructor is called.
Second destructor is called.
First destructor is called.
*/

-------------------------------------------------

In the above program we have constructors and Destructors. Constuctors invoke from the First to the Third while Destructors go just in the Opposite way ie it starts from Third destrucor and goes to First....

No comments: