Hi folks, In this tutorial, We are going to learn What is Constructor in C#? A Constructor is a special type of method which is invoked when we create an instance of the class.

What is Constructor in C#?

A Constructor is a special type of method which is invoked when we create an instance of the class. It has the same name as the class name. A constructor does not have any return type not even void. It is used to assign the initial value to the data member of the class.

For Example, If I have a class called MyClass then the Constructor of the class is created as follows,

public class MyClass

{

public MyClass()

{

//Constructor 

}

}

In the above code snippet, we have a class called MyClass and the constructor of this class is created with the same as the class name.

Types of Constructor:

There are following types of Constructor in C#.

  1. Default Constructor.
  2. Parameterized Constructor.
  3. Copy Constructor.
  4. Private Constructor.
  5. Static Constructor.

We will discuss Default and Parameterized Constructor in this tutorial. Rest of the types we will discuss in next sessions.

Default Constructor:

A constructor with no parameters is called a default constructor. The default constructor initializes all numeric fields to zero and all string and object fields to null inside a class.

using System; 
public class Student 
{ 
public Student() 
{ 
Console.WriteLine("Default Constructor Invoked"); 
} 
} 
class TestStudent{ 
public static void Main(string[] args) 
{ 
Student objStudent1 = new Student(); 
Student objStudent2 = new Student(); 
} 
}

Output:

Default Constructor Invoked

Default Constructor Invoked

Parameterized Constructor:

A Constructor with at least one parameter is called Parameterized Constructor. It can initialize each instance of the class to new values.

using System;

public class Student
{
public int _iRollNo;
public String _sName;

public Student(int iRollNo, String sName)
{
_iRollNo = iRollNo;
_sName = sName;
 
}
public void DisplayRecord()
{
Console.WriteLine("Roll No " + " " + _iRollNo + ". Name " + _sName);
}
} 
class Program
{
 
 
static void Main(string[] args)
{

Student objStudent = new Student(1,"Vinod");
Student objStudent1 = new Student(2, "Ansh");
objStudent.DisplayRecord();
objStudent1.DisplayRecord();
 
Console.ReadLine();
 
}
 
}

Output:

Roll No 1. Name Vinod
Roll No 2. Name Ansh

Point Of Interest for Constructor:

  1. A constructor has the same name as the class name.
  2. A constructor doesn’t have the return type not even void.
  3. A class can have any number of the constructor.
  4. A constructor cannot be declared as abstract final.
  5. A static  constructor cannot be parameterized.

View More:

Conclusion:

I hope you would love this post. Please don’t hesitate to comment for any technical help. Your feedback and suggestions are welcome to me.

Thank You.

Leave a Comment