Constructors in C#

A class constructor is a special member function, which have the same name as class name. It is called automatically when object of the class is created. Constructor does not have return type. Constructor is used to initialize the object.

class Employee
{
    public Employee()
    {            
    }
}


When you create the object of Employee class, constructor will called automatically.

A constructor that does not take any parameters is called a default constructor. In the above given example, constructor is default constructor. If you do not write default constructor in the class, compiler automatically provides default constructor. So we can say that, there is always at least one constructor in every class.

Some important types of constructor are as follows:

  • Default Constructor
  • Parameterized Constructor
  • Static Constructor
  • Private Constructor

Example

using System;
namespace ConsoleApplication1
{
    class Employee
    {
        int empID;
        string empName;
        string empAddress;
        //Default Constructor
        public Employee()
        {
            empID = 0;
            empName = "N/A";
            empAddress = "N/A";
        }
        //Parameterized constructor.
        public Employee(int ID,string name,string address)
        {
            empID = ID;
            empName = name;
            empAddress = address;
        }
        public void showData()
        {
            Console.WriteLine("Employee ID :="+empID);
            Console.WriteLine("Employee Name :="+empName);
            Console.WriteLine("Employee Address :="+empAddress);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee (1,"RAJ","USA");
            emp.showData();
            Console.ReadLine();
        }
    }
}


Output:
Employee ID : =1
Employee Name : =RAJ
Employee Address : =USA

Some of the key things regarding the Constructor are:

  • Constructor name is same as class name
  • A class can have any number of constructors.
  • Constructors are responsible for object initialization
  • A constructor does not have any return type, not even void.
  • Constructor can be overloaded.
  • A class cannot have a virtual constructor
  • A static constructor cannot be a parameterized constructor.
  • Within a class you can create only one static constructor.

Static Constructor

A static constructor is used to initialize any static data. It is called automatically before first instance of class is created. It can only access the static member(s) of the class.

Example

using System;
namespace ConsoleApplication1
{
    class staticConstructor
    {
        static double price;
        static staticConstructor()
        {
            Console.WriteLine("Static constructor called");
            if (price <= 0)
            {
                price = 10;
            }
        }
        public static void showData()
        {
            Console.WriteLine("Price = "+price);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            staticConstructor obj = new staticConstructor();
            staticConstructor.showData();
            Console.ReadLine();
        }
    }
}


Key things about static constructor are:

  • When the class is first loaded, static constructor is called automatically.
  • It can only access the static member(s) of the class.
  • Only one static constructor is allowed.
  • Static constructor does not have any parameter (Overloading is not allowed).
  • Static constructors cannot have access modifiers

Private constructor

If your class contain only static member, then private constructor is good choice. If a class has private constructors and do not have public constructors, then other classes cannot create object of this class. It provides implementation of singleton class pattern.

Example

using System;
namespace ConsoleApplication1
{
    public class PrivateConstructor
    {
        private PrivateConstructor() { }
        public static int Count;
        public static int ShowCount()
        {
            return Count++;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
           // If you uncomment the below code, it will give the error.
           // You cannot create the object, if private constuctor is there.
           // No instance constructor is available.
           // PrivateConstructor obj=new PrivateConstructor()
           
            PrivateConstructor.Count = 100;
            PrivateConstructor.ShowCount();
            Console.WriteLine("New count: {0}", PrivateConstructor.Count);

            Console.ReadLine();
        }
    }
}