find and solve || findandsolve.com
Please wait.....

Constructors In C#

In the C#, A constructor is a member of a class. It is a method in the class that gets executed when a class object is created. Usually, we put the initialization code in the constructor. The constructor name is always the same name as the class. A C# constructor can be public or private.

There are two types of constructors in C#

  • Default constructor
  • Parameterized constructor

C# Default Constructor

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

   using System;  
   public class EmployeeInfo
    {
        public EmployeeInfo()
        {
            Console.WriteLine("Default Constructor");
        }
        public static void Main(string[] args)
        {
            EmployeeInfo obj = new EmployeeInfo();
            EmployeeInfo obj1 = new EmployeeInfo();
        }
    }  

Output

Default Constructor 

Default Constructor 

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

   using System;  
   public class EmployeeInfo
    {
        public EmployeeInfo()
        {
            Console.WriteLine("Default Constructor");
        }
    }
  public class AnotherClassEmployee{
       public static void Main(string[] args)
        {             EmployeeInfo obj = new EmployeeInfo();
            EmployeeInfo obj1 = new EmployeeInfo();
        }
    }  

Output

Default Constructor

Default Constructor 


C# Parameterized Constructor

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

   using System;  
   public class EmployeeInfo
    {
        public int Id;
        public string Name;
        public int Age;
        public EmployeeInfo(int id, string name,int age)
        {
            Id=id;
            Name= name;             Age=age;
        }
        public void display()
        {
            Console.WriteLine(Id + " " + Name+" "+ Age);
        }
   }
   public class OtherClassEmployeeInfo{
       public static void Main(string[] args)         {
            EmployeeInfo obj = new EmployeeInfo(1001, "Sylvia",38);
            EmployeeInfo obj1 = new EmployeeInfo(1002, "Rahul",18);
            obj.display();             obj1.display();
        }
    }  

Output

1001 Sylvia 38

1002 Rahul 28