Introduction:
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 to
interview 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
|
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
|
|||
4 comments :
Hello Suresh ,
I need a registration form with capcha image.How to check capcha text is valid or not,then proceed to login page..
Could u please help me.
Thanks , Saroj Panda
Great valuable blog loved it
thnx
Note: Only a member of this blog may post a comment.