Introduction

Constructor is a special method presented under a class responsible for initializing the variable of that class.

Few points about constructor

Types of Constructors

  1. Default or parameter less Constructor.
  2. Parameterized Constructor.
  3. Copy Constructor.
  4. Static Constructor.
  5. Private Constructor:

Default/parameter less Constructor

If a constructor method doesn’t take any parameters then we call that as default or parameter less.

public class MyClass
{
    // Default Constructor
    public MyClass()
    {
        // Initialization code
    }
}

Parameterized Constructor

If a constructor method takes any parameter then it is called a parameterized constructor. These constructors can be defined by the programmers only but never can be define by implicitly.

public class Car
{
    // Parameterized Constructor
    public Car(string make, string model, int year)
    {
        Make = make;
        Model = model;
        Year = year;
    }
}

Copy Constructor

If we want to create multiple instances with the same values then we use these copy constructors, in a copy constructor the constructor takes the same class as a parameter to it.

class technicalscripter {
 
    // variables
    private string topic_name;
    private int article_no;
 
    // parameterized constructor
    public technicalscripter(string topic_name, int article_no)
    {
        this.topic_name = topic_name;
        this.article_no = article_no;
    }
 
    // copy constructor
    public technicalscripter(technicalscripter tech)
    {
        topic_name = tech.topic_name;
        article_no = tech.article_no;
    }
 
    // getting the topic name and
    // number of articles published
    public string Data
    {
 
        get
        {
            return "The name of topic is: " + topic_name +
                   " and number of published article is: " +
                                    article_no.ToString();
        }
    }
}

Static Constructor

If a constructor is explicitly declared by using static modifier, we call that as Static Constructor. All the constructor we have define till now are non-static. Static constructors are implicitly call no explicit call is required.

public class MyClass
{
    // Static Constructor
    static MyClass()
    {
        // Initialization code for static members
    }
}

Private Constructor

public class Singleton
{
    private static Singleton instance;

    // Private Constructor
    private Singleton()
    {
        // Initialization code
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

Thank you and Happy Learning.