C# Constructors and Destructors

Constructors and Desctructors are important part of class in C#, let's discuss each in detail in this tutorial, with example.

C# Constructor

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:

  • A class can have more than 1 constructor.
  • It should be the same name of class.
  • It never returns value so don’t create constructors with return type.
  • A constructors may be created with our without arguments.

C# Constructor example

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

Types of Constructors

Following are the type of constructors:

  • Default Constructor : When constructors do not have parameters, then it is called the default constructor. These types of constructors have all its instance initialized with no values.
  • Parameterized Constructor : When constructors have parameters, then it is called parameterized constructor. The advantage of a parametrized constructor is that you can initialize each instance of the class with a different value.
  • Copy Constructor :  The constructor which creates an object by copying variables from another object is called a copy constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing instance.
  • Static Constructor : When a constructor is created using a static keyword, it will be invoked only once for all of instances of the class and it is invoked during the creation of the first instance of the class or the first reference to a static member in the class.
  • Private Constructor : When a constructor is created using private keyword it is called as private constructor, it is not possible for other classes to derive from this class, neither is it possible to create an instance of this class

Destructor in C#

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

constructor-destructor-c-sharp-min.png


Share Tweet