Constructors and Desctructors are important part of class in C#, let's discuss each in detail in this tutorial, with example.
Constructor is a special method in C# class, which has same name as it's class name and it is invoked when a object is created.
It is used when we initialize an object of a class. It looks like similar to method but it has the same name as a class.
Example:
//class declared
public class ClassName{
//contructor
public ClassName(){
//do something
}
}
In the above example, as you can see we have Class of Name "ClassName" and we have method of same name "ClassName()" inside the class, which is constructor.
Important points about Constructor:
Let's take a look on more detailed example for constructor
using System;
public class Addition
{
int a, b;
//default contructor
public Addition()
{
a = 100;
b = 175;
}
public static void Main()
{
//an object is created , constructor is called here
Addition obj = new Addition();
Console.WriteLine(obj.a);
Console.WriteLine(obj.b);
}
}
Output:
100
175
Following are the type of constructors:
It is an special method, which has name as Class name just like constructors, but with tilde(~) sign before class name.
Destructors are used to remove instances of classes as soon as class closed. It is very useful way to clean memory and remove all the instances of the program.
Destructors doesn't accept any argument.
Syntax
public class ClassName()
{
//destructors
~ ClassName()
{
//do something
}
}
When a Destructor called it automatically invokes Finalize Method. Finalize method in C# is used for cleaning memory from unused objects and instances. So, when you call the destructor, it actually translates into following code.
protected override void Finalize()
{
try
{
// statements...
}
finally
{
base.Finalize();
}
}
Example
public class Check
{
public Check()
{
Console.WriteLine("Check Object Created. Press Enter to destroy it.");
}
~Check()
{
Console.WriteLine("Destroying First Object");
Console.ReadLine();
}
}
public class Program
{
public static void Main(string[] args)
{
Check ft = new Check();
Console.ReadLine();
}
}
Output