A constructor is a special type of method which is used to initialize object when it is created. To understand its definition we take an example.
You are creating a class in which you are required a temperature value in centigrade and in then use that value in entire class. A constructor is used here for initialize object with value.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Constructor_Example
{
    class CalculateHeat
    {
        public int temp=0;
        //Constructor Creation
        public CalculateHeat(int val)
        {
            temp = Convert.ToInt32(val);
        }
        public CalculateHeat(string Message)
        {
            Console.WriteLine(Message.ToString());
        }
        public void calculate()
        {
            decimal fahrenheit = Convert.ToDecimal(temp * 1.8 + 32);
            Console.WriteLine("{0} degree centigrade into fahrenheit = {1}", temp, fahrenheit);
        }
        //Destructor Initialization, It will clean memory at the end and frees up system resources.
        ~CalculateHeat()
        {
            Console.WriteLine("Destructor Initializes, Cleanup Process Complete");
            Console.ReadLine();
        }
    }
    class Program
    {
        public static void Main(String[] args)
        {
            CalculateHeat cl = new CalculateHeat(36);
            cl.calculate();
            CalculateHeat c2 = new CalculateHeat("I am second constructor");          
        }
    }
}
Constructor Creating
In below program, we have created two constructors and both need a parameter passed to it while initialize object. One constructor is for getting integer value and another one is for displaying message on screen. Notice that both constructors have same name as class but have different parameter. You may create as more constructor as you need with different parameter or number of parameter.
//Constructor Creation
public CalculateHeat(int val)
{
     temp = Convert.ToInt32(val);
}
public CalculateHeat(string Message)
{
     Console.WriteLine(Message.ToString());
}
Object Initialization
In the Main method we have initialized object and while initialization of object we passed parameter in it.
public static void Main(String[] args)
{
   CalculateHeat cl = new CalculateHeat(36);
   cl.calculate();
   CalculateHeat c2 = new CalculateHeat("I am second constructor");            
}
Destructor
We have also define Destructor in this program to clean up system resources and cleanup memory. It is good practice to use destructors to avoid security breaches.
//Destructor Initialization, It will clean memory at the end and frees up system resources.
~CalculateHeat()
{
    Console.WriteLine("Destructor Initializes, Cleanup Process Complete");
    Console.ReadLine();
}

Leave a Reply

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