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. The 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 does not have a return type.
A constructor must be the same as the class name The method name may or may not be the 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 a constructor the class will automatically call the default constructor when an object is created.

Example

using System;
namespace DefaultConstructor_Demo
{
    public class Customer
    {
        public string firstName;
        public string lastName;

        public Customer()
        {
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();
            customer.firstName = "Farhan";
            customer.lastName = "Ahmed";

            Console.WriteLine("Full Name: " + customer.firstName + " " + customer.lastName);
            Console.ReadLine();
        }
    }
}

Parameter Constructor

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

Example

using System;
namespace ParameterConstructor_Demo
{
    class ParameterConstructor
    {
        public int FirstNumber;
        public int SecondNumber;

        public ParameterConstructor(int firstNumber, int secondNumber)
        {
            FirstNumber = firstNumber;
            SecondNumber = secondNumber;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ParameterConstructor p = new ParameterConstructor(10, 20);
            int Result = p.FirstNumber + p.SecondNumber;

            Console.WriteLine("Total:" + Result);
            Console.ReadLine();
        }
    }
}

Copy Constructor

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

Example

using System;
namespace CopyConstructor_Demo
{
    public class Employee
    {
        public string firstName;
        public string lastName;
        public string position;
        public int salary;

        public Employee()
        {
                  
        }
        // Copy constructor.
        public Employee(Employee employee)
        {
            firstName = employee.firstName;
            lastName = employee.lastName;
            position = employee.position;
            salary = employee.salary;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            Employee emp1 = new Employee(emp);
            Console.WriteLine("Enter your first name:");
            emp1.firstName = Convert.ToString(Console.ReadLine());
            Console.WriteLine("Enter your last name:");
            emp1.lastName = Convert.ToString(Console.ReadLine());
            Console.WriteLine("Enter your position:");
            emp1.position = Convert.ToString(Console.ReadLine());
            Console.WriteLine("Enter your salary:");
            emp1.salary = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("First Name:" + emp1.firstName);
            Console.WriteLine("Last Name:" + emp1.lastName);
            Console.WriteLine("Position:" + emp1.position);
            Console.WriteLine("Salary:" + emp1.salary);
        }
    }
}

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

using System;
namespace StaticConstructor_Demo
{
    public class Customer
    {
        public string firstName;
        public string lastName;
        public static string discount;
        public Customer(string FirstName, string LastName)
        {
            firstName = FirstName;
            lastName = LastName;
        }
        static Customer()
        {
            discount = 10 + "%";
        }
        public void CustomerDetails()
        {
            Console.WriteLine("Full Name:{0}", firstName + " " + lastName);
            Console.WriteLine("Discount:{0}", discount + "\n");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Customer c1 = new Customer("Farhan", "Ahmed");
            Customer c2 = new Customer("Abdul", "Jabbar");
            c1.CustomerDetails();
            c2.CustomerDetails();
            Console.ReadLine();
        }
    }
}

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 a private constructor we can ensure that no more than one object can be created at a time

  • One use of a private constructor is when we have only a static member.
  • It provides the implementation of a singleton class pattern.
  • Once we provide a constructor (private/public/any) the compiler will not add the no parameter public constructor to any class.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrivateConstructor_Demo
{
    public class Candidate
    {
        private Candidate()
        {            
        }
        public static int CandidateVisitedForInterview;  
        public static int CountCandidate()
        {
            return ++CandidateVisitedForInterview;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // The following comment line will throw an error because constructor is inaccessible
            //Candidate candidate = new Candidate();

            Candidate.CandidateVisitedForInterview = 20;
            Candidate.CountCandidate();

            Console.WriteLine("Interviewed candidates: {0}", Candidate.CandidateVisitedForInterview);
            Console.ReadLine();
        }
    }
}

Here is the detailed tutorial on Constructors in C#.

https://www.c-sharpcorner.com/UploadFile/0c1bb2/constructors-and-its-types-in-C-Sharp/


Similar Articles