C Sharp Constructor

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# Constructor

In C#, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C# has the same name as class or struct.

There can be two types of constructors in C#.

  • Default constructor
  • Parameterized constructor

C# Default Constructor

A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.

C# Default Constructor Example: Having Main() within class

  1. using System;  
  2.    public class Employee  
  3.     {  
  4.         public Employee()  
  5.         {  
  6.             Console.WriteLine("Default Constructor Invoked");  
  7.         }  
  8.         public static void Main(string[] args)  
  9.         {  
  10.             Employee e1 = new Employee();  
  11.             Employee e2 = new Employee();  
  12.         }  
  13.     }  

Output:

Default Constructor Invoked 
Default Constructor Invoked

C# Default Constructor Example: Having Main() in another class

Let's see another example of default constructor where we are having Main() method in another class.

  1. using System;  
  2.    public class Employee  
  3.     {  
  4.         public Employee()  
  5.         {  
  6.             Console.WriteLine("Default Constructor Invoked");  
  7.         }  
  8.     }  
  9.    class TestEmployee{  
  10.        public static void Main(string[] args)  
  11.         {  
  12.             Employee e1 = new Employee();  
  13.             Employee e2 = new Employee();  
  14.         }  

Output:

Default Constructor Invoked 
Default Constructor Invoked

C# Parameterized Constructor

A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects.

  1. using System;  
  2.    public class Employee  
  3.     {  
  4.         public int id;   
  5.         public String name;  
  6.         public float salary;  
  7.         public Employee(int i, String n,float s)  
  8.         {  
  9.             id = i;  
  10.             name = n;  
  11.             salary = s;  
  12.         }  
  13.         public void display()  
  14.         {  
  15.             Console.WriteLine(id + " " + name+" "+salary);  
  16.         }  
  17.    }  
  18.    class TestEmployee{  
  19.        public static void Main(string[] args)  
  20.         {  
  21.             Employee e1 = new Employee(101, "Sonoo", 890000f);  
  22.             Employee e2 = new Employee(102, "Mahesh", 490000f);  
  23.             e1.display();  
  24.             e2.display();  
  25.   
  26.         }  
  27.     }  

Output:

101 Sonoo 890000
102 Mahesh 490000