Constructors in C#

Constructors are the methods that are invoked when an instance of a class or struct is created. Constructors are generally used to initialize the private fields in the class or struct when an instance of the class is created. A default constructor is created for a class when no constructor is explicitly defined by the programmer. So, each class will always have at least one constructor even if none is created by the programmer. This default constructor would initialize all the numeric data values to zero and objects and string to null.




Syntax:

[Access Specifier] Class Class Name
{
    //Constructor
    [Access Specifier] Class Name([Paramaters])
    {
        //Your Code
    }
}

Above is the General Syntax of Constructor the access specifier various according to the need of the program.




Features:

Key features of constructors are:

  • Any number of constructors can be there for a class.

  • It doesn’t have a return type. This includes even void.

  • The constructor of a static class can never be parameterized.

  • Only one static constructor can be created within a class.

  • Constructors can be overridden.



Types of Constructor

  1. Default Constructor

  2. Parameterized Constructor

  3. Copy Constructor

  4. Static Constructor

  5. Private Constructor


1. Default Constructor

When no parameter is passed to the constructor, the constructor is said to be a default constructor. The major drawback of a default constructor is that we cannot initialize the different instances of classes with different values as all the instances will be created using the same values that are defined in the default constructor. This default constructor would initialize all the numeric data values to zero and objects and string to null.