Here I am going to explain what is the constructor and why it is used what is the purpose of constructor in c#. The constructor is used to assign a value. Constructor name and class name must be same. Implement the constructor in a class. You must declare the constructor as public because then only you can access it from Main class.
Types of Constructor:
- Default Constructor
- Parametrised Constructor
Default Constructor is nothing but while creating the object for the class you will use a class name with a new keyword and it also has a no parameter and this is called the default constructor. The default constructor has no parameter.
The Constructor which has parameter is called as parameterised constructor.
public Myclass(int firstnumber, int secondnumber)
How to pass a value for the constructor??
You can pass a value to constructor while creating the object for the class in Main class.
MyClass mObj=new Constructor(5,4); //Passing value to the constructor.
Hope, now you know how to use and implement a constructor in c#. If you have any doubt you may leave a comment here. I will help you as soon as possible.