What is Constructor in c# And Use of It’s  ???

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:

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.

Parameterised Constructor:

The Constructor which has parameter is called as parameterised constructor.

Syntax:
Public Class_Name(parameter)
{
fieldname=parametername;
}
Example:

//Constructor

public Myclass(int firstnumber, int secondnumber)

{

int number1=firstnumber;

int number2=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.

Example:

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.