What are the different types of constructors in C#?
In C#, a constructor is a method type that is automatically created with an instance of a class. There are 5 types of constructors:
1. Default Constructor
A default constructor is a type of constructor without any parameters. Basically, it does not take parameters. The default constructor initializes all numeric fields in the class to zero, and all string and object fields to null. With a default constructor, every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class to different values.
2. Parametrized Constructor
A parametrized constructor is a constructor with at least one parameter. It allows one to initialize each instance of the class to different values.
3. Copy Constructor
The copy constructor creates an object by copying variables from another object. It basically initializes a new instance to the values of an existing instance.
4. Static Constructor
The static constructor can be invoked only once for all of instances of the class. It can be invoked only during the creation of the first instance of the class or the first reference to a static member in the class. The static constructor is primarily used to initialize static fields of the class. It is also used write the code that needs to be executed only once. It also cannot access modifiers or have parameters. It also cannot be called directly.
5. Private Constructor
A private constructor is created with a private specifier. As it is private, is not possible for other classes to derive from this class. It is also not possible to create an instance of this class. Private constructors are usually used in classes that contain static members only.