Feb 24, 2014

C# - Destructor in C# with Example

ntroduction:

Here I will explain what is destructor in c# with example, use of destructor in c#.net. Destructor in c# is a special method of a class which will invoke automatically when an instance of the class is destroyed. Destructor is used to write a code that needs to be executed while an instance is destroyed.

Description:

  Now I will explain destructor in c#.net with example.

To create destructor we need to create method in a class with same name as class preceded with ~ operator.
Syntax of Destructor
class SampleA
{
public SampleA()
{
// Constructor
}
~SampleA()
{
// Destructor
}
}
Example of Destructor

In below example I created a class with one constructor and one destructor. An instance of class is created within a main function. As the instance is created within the function, it will be local to the function and its life time will be expired immediately after execution of the function was completed.
using System;
namespace ConsoleApplication3
{
class SampleA
{
// Constructor
public SampleA()
{
Console.WriteLine("An  Instance  Created");
}
// Destructor
~SampleA()
{
Console.WriteLine("An  Instance  Destroyed");
}
}
class Program
{
public static void Test()
{
SampleA T = new SampleA(); // Created instance of class
}
static void Main(string[] args)
{
Test();
GC.Collect();
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below
Output
An instance created
An instance destroyed
I hope it helps you to know about destructor concept.

No comments:

Post a Comment