Constructor
In C#, a constructor is a special method in a class that is automatically called when an object of that class is created. It can be used to set initial values for fields.
Types of Constructor
1.Default Constructor
2.Parameterized Constructor
3.Copy Constructor
4.Private Constructor
5.Static Constructor
Definetions:
1.Default Constructor:
If a class doesn't have any explicitly defined constructors, C# provides a default constructor with no parameters.
2.Parameterized Constructor:
A constructor having at least one parameter is called as parameterized constructor. It can initialize each instance of the class to different values.
3.Copy Constructor:
This constructor creates an object by copying variables from another object. Its main use is to initialize a new instance to the values of an existing instance.
4.Private Constructor:
If a constructor is created with private specifier is known as Private Constructor. It is not possible for other classes to derive from this class and also it’s not possible to create an instance of this class.
Points To Remember :
It is the implementation of a singleton class pattern.
use private constructor when we have only static members.
Using private constructor, prevents the creation of the instances of that class.
5.Static Constructor:
Static Constructor has to be invoked only once in the class and it has been invoked during the creation of the first reference to a static member in the class. A static constructor is initialized static fields or data of the class and to be executed only once.
Points To Remember :
It can’t be called directly.
When it is executing then the user has no control.
It does not take access modifiers or any parameters.
It is called automatically to initialize the class before the first instance created.
Refernce: GFG
Comments
Post a Comment