Destructor in Console Application



In previous console application post we learned about create console application, namespaces in c# and constructor in c# console application.

In this c# .net  tutorials we will  learn what is destructor and how to use destructor in c#.net.

Destructor in C#

Destructor are used to destruct instances of classes.
In .net framework there is a facility to cleanup unused or un-referenced object automatically called garbage collection.
Some time we need to cleanup unused object manually, for destruct manually unused object we use destructor method.

A class have only one destructor.
Destructor will call after execution of program.

Syntax of destructor :

~ myclass()

{

}

Class DesExample
{
~ DesExample() // destructor
{

}
}

Example of destructor in c#.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesctExample
{
class MyExample
{ 
public MyExample()//Default constructor
{
Console.WriteLine("Example of Default Constructor");
}

~MyExample() // Destructor
{
Console.WriteLine("Example of Destructor"); 
}
}
class Program
{
static public void Test()
{
MyExample obj = new MyExample();
}
static void Main(string[] args)
{
Test();
GC.Collect();
Console.ReadLine();
}
}
}

The output of destructor example is :

Example of Default Constructor
Example of Destructor

 

Leave a Reply

Your email address will not be published. Required fields are marked *