Different Types Of Constructor In C#

Introduction

In this article, we will learn about constructors and types of constructors in C#. There are five different types of constructors in C#. To create a constructor, we use the shortcut key ctor tab twice. It will create a respective class constructor. A constructor is used for creating objects of a class. Following is the list of constructors in C#.

  • Default constructor
  • Parameterized constructor
  • Copy constructor
  • Static constructor
  • Private constructor

What is a constructor?

A constructor is a special method that is used to initialize an object. A constructor is invoked at the time of an object creation. Constructor name must be the same as its class name. A constructor must have no explicit return type.

Different between Constructors and Method

Constructor  Method
A constructor is used to initialize an object A method is used to expose the behavior of an object
The constructor must not have a return type. The method has or not have a return type.
A constructor must be the same as the class name Method name may or may not be same as the class name
A constructor is invoked implicitly. A method is invoked explicitly.

Default Constructor

A constructor without any parameters is called a default constructor. If we do not create constructor the class will automatically call default constructor when an object is created.

Example

  1. using System;  
  2. namespace DefaultConstructor_Demo  
  3. {  
  4.     public class Customer  
  5.     {  
  6.         public string firstName;  
  7.         public string lastName;  
  8.         public Customer()  
  9.         {  
  10.   
  11.         }  
  12.     }  
  13.     class Program  
  14.     {  
  15.         static void Main(string[] args)  
  16.         {  
  17.             Customer custormer = new Customer();  
  18.             custormer.firstName = "Farhan";  
  19.             custormer.lastName = "Ahmed";  
  20.   
  21.             Console.WriteLine("Full Name:"+custormer.firstName+ " "+ custormer.lastName);  
  22.             Console.ReadLine();  
  23.   
  24.         }  
  25.     }  
  26. }  

Parameter Constructor

A constructor with at least one parameter is called a parametrized constructor.

Example

  1. using System;  
  2. namespace ParameterConstructor_Demo  
  3. {  
  4.     class ParameterConstructor  
  5.     {  
  6.         public int FirstNumber;  
  7.         public int SecondNumber;  
  8.   
  9.         public ParameterConstructor(int firstNumber, int secondNumber)  
  10.         {  
  11.             FirstNumber = firstNumber;  
  12.             SecondNumber = secondNumber;  
  13.         }  
  14.     }  
  15.     class Program  
  16.     {  
  17.         static void Main(string[] args)  
  18.         {  
  19.             ParameterConstructor p = new ParameterConstructor(10, 20);  
  20.             int Result = p.FirstNumber + p.SecondNumber;  
  21.   
  22.             Console.WriteLine("Total:" + Result);  
  23.             Console.ReadLine();  
  24.         }  
  25.     }  
  26. }  

Copy Constructor

The constructor which creates an object by copying variables from another object is called a copy constructor.

Example

  1. using System;  
  2. namespace CopyConstructor_Demo  
  3. {  
  4.     public class Employee  
  5.     {  
  6.        public string firstName;  
  7.        public string lastName;  
  8.        public string position;  
  9.        public int salary;  
  10.         public Employee()  
  11.         {  
  12.                   
  13.         }  
  14.         // Copy constructor.  
  15.         public Employee(Employee employee)  
  16.         {  
  17.             firstName = employee.firstName;  
  18.             lastName  = employee.lastName;  
  19.             position  = employee.position;  
  20.             salary    = employee.salary;  
  21.         }  
  22.   
  23.     }  
  24.     class Program  
  25.     {  
  26.         static void Main(string[] args)  
  27.         {  
  28.             Employee emp = new Employee();  
  29.             Employee emp1 = new Employee(emp);  
  30.    
  31.             Console.WriteLine("Enter your first name:");  
  32.             emp1.firstName = Convert.ToString(Console.ReadLine());  
  33.             Console.WriteLine("Enter your last name:");  
  34.             emp1.lastName = Convert.ToString(Console.ReadLine());  
  35.             Console.WriteLine("Enter your position:");  
  36.             emp1.position = Convert.ToString(Console.ReadLine());  
  37.             Console.WriteLine("Enter your salary:");  
  38.             emp1.salary = Convert.ToInt32(Console.ReadLine());  
  39.   
  40.             Console.WriteLine("First Name:" + emp1.firstName);  
  41.             Console.WriteLine("Last Name:" + emp1.lastName);  
  42.             Console.WriteLine("Position:" + emp1.position);  
  43.             Console.WriteLine("Salary:" + emp1.salary);  
  44.         }  
  45.     }  
  46. }  

Static Constructor

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

Characteristic of static constructor

  • A static constructor does not take any access modifiers.
  • A static constructor does not have a parameter.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control over when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • A class can have only one static constructor.
  • It can access only static members of a class.

Example

  1. using System;  
  2. namespace StaticConstructor_Demo  
  3. {  
  4.     public class Customer  
  5.     {  
  6.         public string firstName;  
  7.         public string lastName;  
  8.         public static string discount;  
  9.   
  10.         public Customer(string FirstName, string LastName)  
  11.         {  
  12.             firstName = FirstName;  
  13.             lastName = LastName;  
  14.         }  
  15.         static Customer()  
  16.         {  
  17.             discount = 10+"%";  
  18.         }  
  19.         public void CustomerDetails()  
  20.         {  
  21.             Console.WriteLine("Full Name:{0}", firstName +" "+lastName );  
  22.             Console.WriteLine("Discount:{0}",discount + "\n");  
  23.         }    
  24.     }  
  25.     class Program  
  26.     {  
  27.         static void Main(string[] args)  
  28.         {  
  29.             Customer c1 = new Customer("Farhan","Ahmed");  
  30.             Customer c2 = new Customer("Abdul""Jabbar");  
  31.             c1.CustomerDetails();  
  32.             c2.CustomerDetails();  
  33.             Console.ReadLine();  
  34.         }  
  35.     }  
  36. }  
 
A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class. The use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects created to one. Using private constructor we can ensure that no more than one object can be created at a time
  • One use of private constructor is when we have the only static member.
  • It provides the implementation of singleton class pattern.
  • Once we provide constructor (private/public/any) the compiler will not add the no parameter public constructor to any class.

Example

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace PrivateConstructor_Demo  
  8. {  
  9.     public class Candidate  
  10.     {  
  11.         private Candidate()  
  12.         {  
  13.                   
  14.         }  
  15.         public static int CandidateVisitedForInterview;  
  16.         public static int CountCandidate()  
  17.         {  
  18.             return ++CandidateVisitedForInterview;  
  19.         }  
  20.   
  21.     }  
  22.     class Program  
  23.     {  
  24.         static void Main(string[] args)  
  25.         {  
  26.             // The following comment line will throw an error because constructor is inaccessible  
  27.             //Candidate candidate = new Candidate();  
  28.             Candidate.CandidateVisitedForInterview = 20;  
  29.             Candidate.CountCandidate();  
  30.             Console.WriteLine("Interviewed candidates: {0}", Candidate.CandidateVisitedForInterview);  
  31.             Console.ReadLine();  
  32.         }  
  33.     }  
  34. }
Here is detailed tutorial on Constructors in C#.