Constructor in C# with examples

What is Constructor ?

A Constructor is a special method of a Class, which is used to initialize the members of the same class. Whenever an Object of a class is created , a Constructor is called by default. Constructor do not return values and always have the same name as the Class.

Image is not available

As shown in above image , I have created a Employee class and it has three properties that is EmployeeId, Name and Department. I have created a Constructor with same name as class that is Employee and it has a public specifier. Constructor name always be same as class name and it is used for initialization of members in any class. We have initialize EmployeeId with 1 , Name with "John Saffer" and Department with "IT". Below is the code example for constructor so that you can easily understand to it.


 public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }=String.Empty;
        public string Department { get; set; }=String.Empty;

        public Employee()
        {
            EmployeeId = 1;
            Name = "John Saffer";
            Department = "IT";
        }
    } 

Types of Constructors in C#

There are 5 Types of Constructors are available in C# , below is the list of Constructors in C#.

  • Default Constrcutor
  • Private Constructor
  • Static Constructor
  • Copy Constructor
  • Parameterized Constructor

Default Constructor ?

Default constructor is a parameterless constructor and invoked every time when an object is created for class. Default constructor always set some default values to members as like 0 for int members and null for string and objects. Below is the image for explaining the default constructor.

Image is not available

As you can see in above image Employee is the default constructor there is no initialization for EmployeeId, Name and Department when we create an object it will automatically set 0 for default values.


 public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
        public Employee()
        {
            Console.WriteLine("Called a default constructor and set 0 for int and null for strings");
        }
    } 

As you can see in below image we have created a object for Employee class in program.cs file and write the values of EmployeeId and Name into the console.

Image is not available

 Employee emp = new Employee();
Console.WriteLine(emp.EmployeeId);
Console.WriteLine(emp.Name); 

Output of the Program

Image is not available

Parameterized Constructor ?

Parameterized constructor is a constructor with minimum one parameter and set a different value for parameter every time when an object is created for class. Parameterized constructor always set values that is provided in object creation for parameter list. Below is the image for explaining the Parameterized constructor.

Image is not available

As you can see in above image Employee is the Parameterized constructor with two parameters one is type int and other is type string. empid is the int parameter and name is the string parameter and we have initialised these parameter inside the constructor as you can see in the above image and while creating the object we need to pass these parameter values..


  public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
        public Employee(int empid,string name)
        {
            this.EmployeeId = empid;
            this.Name = name;
        }
    } 

As you can see in below image we have created a object for Employee class in program.cs file and pass the values for empid and name during the object creation so that while creating the constructor these will initialize into the constructor .

Image is not available

 Employee emp = new Employee(25,"James cotlin");
Console.WriteLine("First Parameter is  " +  emp.EmployeeId);
Console.WriteLine("Second Parameter is  " +  emp.Name); 

Output of the Program

Image is not available

Copy Constructor ?

As the name suggest it has a copy feature means Copy constructor is a constructor used for creating an object by copying the variables from other objects . It is mainly used for initializing new values to variables from existing variables.

Image is not available

As you can see in above image Employee is the Parameterized constructor with three parameters one is type int and other is type string and third is also type string. empid is the int parameter and name and department is the string parameter and we have initialised these parameter inside the constructor as you can see in the above image and while creating the object we need to pass these parameter values..
As our concern is copy construtor so we have created other constructor and passed a object of Employee class as a parameter into it and initializes the new variables with existing variables by emp object in below code example.


  public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
        public Employee(Employee emp)
        {
            EmployeeId = emp.EmployeeId;
            Name = emp.Name;
            Department = emp.Department;
        }
        public Employee(int employeeId, string name, string department)
        {
            EmployeeId = employeeId;
            Name = name;
            Department = department;
        }
    } 

As you can see in below image we have created one object for Employee class in program.cs file and pass the values for empid , name and department in construtor then we have created a second object of employee class and we have passed first object into the constructor then it will copy the values from object one that emp1 to object 2 that is emp2 using the constructor invocation.

Image is not available

Employee emp1 = new Employee(25,"William Tell","CS");
Employee emp2 = new Employee(emp1);
Console.WriteLine("First Parameter Copied from first object emp1 is  " +  emp2.EmployeeId);
Console.WriteLine("Second Parameter Copied from first object emp1 is  " +  emp2.Name);
Console.WriteLine("Third Parameter Copied from first object emp1 is  " + emp2.Department); 

Output of the Program

Image is not available

Private Constructor ?

Private constructor is created by using the private specifier with constructor. We can not create an instance of a class having the private constructor and no any other class will inherit the class directly in which private constructor is defined.

Image is not available

As you can see in above image we have created a private constructor of Employee class and one static property EmployeeId of type int. We also created a method named EmployeesCount() to count the EmployeeId for testing the constructor workflow.


 public class Employee
    {
        public static int EmployeeId { get; set; }          
        private Employee()
        {

        }
        public static int EmployeesCount()
        {
            return EmployeeId++;
        }
    } 
Image is not available

If you tried to create an object of Class having the private constructor it will generate an error as shown in Above image.

Image is not available

As you can see in above image we have tried to create an object for Employee class in program.cs file but we got an error so that we commented the first line to creating the object of Employee class. To access the members of class we have to declared them static then we can access them directly we class name as like in above image we have access EmployeeId with class name Employee and set the values for it and then we also call the EmployeesCount() method for incrementing the EmployeeId count. You can also find the same code in below code example.


//Employee emp1 = new Employee();     It will generate an error when creating an object
Employee.EmployeeId = 1000;
Employee.EmployeesCount();
Console.WriteLine("Employee Count is "+ Employee.EmployeeId);
Employee.EmployeesCount();
Console.WriteLine("Employee Count is " + Employee.EmployeeId);
 

Output of the Program

Image is not available

When we tried to inherit the Employee class that has a private constructor with ChildClassA then compiler throws an error for it so that we can not inherit the class which contains the private constructor in it. Below is the image attached in which you can see the error thrown by compiler when inheriting a class contains the private constructor.

Image is not available

Static Constructor ?

Static constructor is created by using the Static specifier with constructor. We can create a Static constructor in Static Class as well as non Static Class Also. Static Constructor invoked only once no matter how many objects are created. If you have created more than one object then only first object reference will invoked the Static constructor.
Static Constructor always invoked before the instance constructors.

Image is not available

As you can see in above image we have created a static constructor of Employee class and one Instance Constructor. We also created a method named PrintFullName() to call when object of Employee class is created.


 public   class Employee
    {       
        static Employee()
        {
            Console.WriteLine("This is Static Constructor of Employee Class");
        }
        public Employee()
        {
            Console.WriteLine("This is Instance Constructor of Employee Class");
        }
        public void PrintFullName()
        {
            Console.WriteLine("Employee Full Name is Ricky Martin");
        }
    } 

We can not use modifiers with static constructor as shown in below image when we use the modifier it will generate an error.

Image is not available

Now we have created the three objects of Employee classs and called the PrintFullName() method with all the three objects as shown in below image.

Image is not available

//Employee emp1 = new Employee();     It will generate an error when creating an object
Employee.EmployeeId = 1000;
Employee.EmployeesCount();
Console.WriteLine("Employee Count is "+ Employee.EmployeeId);
Employee.EmployeesCount();
Console.WriteLine("Employee Count is " + Employee.EmployeeId);
 

As you can see in above image and code we have created 3 object for Employee class in program.cs file and with each object we call the instance method . Static constructor will invoked only once and instance constructor will be invoked every time means it will invoke for 3 times and Static constructor will be called before all the constructors as shown in below output window.

Output of the Program

Image is not available

Important Details on Constructor

A Derived Class can not inherit the Constructor of its Base Class. All the Derived Classes have their own default Constructor.

When you intiantiate a Derived Class , first the Constructor of Base Class is called and then derived class Constructor is called.
The Constructor of Base Class is initializes the members of the Base Class before derived class constructor is executed.

Image is not available
Image is not available
Image is not available

As Shown in above images I have created a Base Class Employee and inside the Employee Class , Created a Static Constructor and a instance constructor and a void method also I have created a ChildClassA and inherits it from Employee Class and inside the Child class I have created a Static and a instance Constructor and then called it from program.cs file as shown in above images. Static constructor always called before the instance constructor and then base class constructor called then child class constructors.

Output of the Program

Image is not available
Points to Remember :-
  • The purpose of a Class Constructor is to initialize Class fields. A class Constructor is automatically called when an instance of a class is created.
  • Constructor do not return values and always have the same name as the Class.
  • Constructors are not mandatory. If we do not provide a constructor , a default parameterless constructor is automatically provided by C#.
  • Constructors can be overloaded by the Name and type of Parameters.
  • If a constructor is used to create a copy of an existing object as new Object ,then the constructor is called a copy constructor.
  • Copy constructor takes the reference of the Object to be copied as an argument.
  • C# does not provide the copy constructor by default.

Destructor in C#

A Destructor or finalizer is called when the Object is finally destroyed and the garbage is collected.
Points to Remember :-

  • Destructor have the same name as the Class with ~ symbol infornt of them.
  • Destructor does not take any parameters and do not return a value.
  • Destructors are places where you could put code to release any resources your class was holding during its lifetime.
  • Destructors are normally called when the C# garbage collector decides to clean your Object from memory.
  • C# has a garbage collection mechanism that runs to destroy an Object when its reference counts drops to 0.
  • We can also destroy the objects that are no longer used ,by calling the destructor in the program.

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.