Saturday, 18 January 2014

C# - Destructor in C# with Example

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:

In previous posts I explained constructors in c#, polymorphism in c# with example, private constructor in c#, static constructor in c#, delegates example in c#, sealed class in c#, using statement in c#, OOPS examples in c# and many articles relating tointerview questions in c#, asp.net, SQL server, JavaScript, jQuery. 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. If you want to know more about oops concept check this link oops concepts

No comments:

Post a Comment