Constructors in C# with Example
*PTR– Point To Remember
A constructor is a method in the class which gets executed when its object is created is called as constructor.
Constructors can be classified into 5 types
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Static Constructor
- Private Constructor
Default Constructor : A constructor without any parameters is called as default constructor.
PTR: every instance of the class will be initialized to same values Not Different values
Parameterized Constructor :A constructor with at least one parameter is called as parameterized constructor.
Public ConstTest (Int X ,Int Y)
PTR: you can initialize each instance of the class to different values
Copy Constructor: A parameterized constructor that contains a parameter of same class type is called as copy constructor.
Public ConstTest ()
Public ConstTest (ConstTest T )
// Access The property of T.name
PTR: initialize new instance to the values of an existing instance.
Static Constructor : You can create a constructor as static and when a constructor is created as static
Static ConstTest ()
PTR: it will be invoked only once for any number of instances of the class and it is during the creation of first instance of the class
Private Constructor :You can also create a constructor as private. When a class contains at least one private constructor
Private ConstTest ()
PTR: restrict the class from being instantiated