C# Constructor

In C#, a constructor is the member of the class and is automatically invoked once the object of the class is created. It is like a method in a program and is used for the initialization of the data members of a newly created object.

class Example
{   
  .......
  // Constructor
  public Example() {
    //Object initialization  
  }
  .......
}


//creating oject
Example obj = new Example(); 

Two types of C# constructors

  1. Default constructor
  2. Parameterized constructor

Default Constructor in C#

A constructor without any parameters is called a default constructor and is invoked at the time of creating the object of the class.

Example: Default C# Constructor

using System;  

   public class Student  
   {  
      public Student()  
      {  
          Console.WriteLine("Constructor Called");  
      }  
      public static void Main(string[] args)  
      {  
          Student std1 = new Student();  
          Student std2 = new Student();  
      }  
   }  

Output:

Constructor Called
Constructor Called

As you can see, that the constructor is called every time we create a new object of the class. And since it is a default constructor, it has no parameter.


Parameterized Constructor in C#

A Constructor having a specific number of parameters is called Parameterized Constructor. Passing parameters is useful when you want to assign a different initial value to distinct objects.

Example: Parameterized C# Constructor

using System; 
 
 public class Student  
 {  
     public int roll;   
     public String name;  
     public float score;  
        
     //constructor
     public Student(int r, String n, float s)  
     {  
         roll = r;  
         name = n;  
         score = s;  
     }  
     public void display()  
     {  
         Console.WriteLine(roll + " " + name + " " + score);  
     }  
 }  

 class StudenInfo
 {  
    public static void Main(string[] args)  
    {  
       Student std1 = new Student(1101, "Shaun", 80.5f);  
       Student std2 = new Student(1102, "Garen", 90f);  
            
       std1.display();  
       std2.display();  
  
    }  
 }   

Output:

1101 Shaun 80.5
1102 Garen 90

As you can see the student details are initialized and displayed for every object created for the Student class in a program.