C# Constructors

In C#, Constructor is the special method with no return type. It is invoked automatically at the time of object creation. Its name must be the same as the class or struct's name. In C#, Constructors are of two types

  1. Default Constructors
  2. Parameterized Constructors
C# Default Constructor: Default constructor is the one which doesn't take any argument. It is invoked automatically at the time of object creation. If a class doesn't have any default and parameterized constructor then the compiler implicitly calls the base class constructor which initializes every variable to its default value. Let's see an example of C# Default Constructor.
using System;
public class Employee
{
            public Employee()
            {
                        Console.WriteLine("Default constructor invoaked");
            }
}
public class MainClass{
public static void Main (string[] args)
{
            Employee emp=new Employee();
}
}
Output
Default constructor invoked
C# Parameterized Constructor: In C#, Parameterized Constructor is the one which accepts parameters at the time of object creation. It initializes the class data with the parameters that are passed at the time of object creation.
Example: Let's see an example of initializing class data with the parameterized constructor.
using System;
public class Employee
{
            int id;
            string name;
            public Employee(int emp_id,string emp_name)
            {
                        id=emp_id;
                        name=emp_name;
            }
            public void display()
            {
                        Console.WriteLine(id+" "+name);
            }
}
public class MainClass{
public static void Main (string[] args)
{
            Employee emp=new Employee(101,"Ayush Sharma");
            emp.display();          
}
}
Output
101 Ayush Sharma