C Sharp Constructor

C# Constructor

A constructor in C# is invoked automatically at the time of object creation. It is a special method having the same name as class or struct and is generally used to initialize the data members of a new object. The constructor in C# has the same name as class or struct. A constructor in C# can be either of the two types.

  • Default constructor
  • Parameterized constructor

C# Default Constructor:

A default constructor is the one with no argument which is invoked at the time of object creation.

Example 1:

using System;  
   public class Cities  
    {  
        public Cities()  
        {  
            Console.WriteLine("Hello World!!");  
        }  
        public static void Main(string[] args)  
        {  
            Cities c1 = new Cities();  
            Cities c2 = new Cities();  
        }  
    }

Output:

Explanation:

In the above example, we are creating a default constructor. Here, we are using the Main() method in the class.

Example 2:

using System;  
   public class Cities  
    {  
        public Cities()  
        {  
            Console.WriteLine("Hello World!!");  
        }  
    }  
   class Details{  
       public static void Main(string[] args)  
        {  
            Cities c1 = new Cities();  
            Cities c2 = new Cities();  
        }  
    }

Output:

Explanation:

In the above example, we are creating a default constructor. Here, we are using the Main() method in another class.

C# Parameterized Constructor:

A parameterized constructor is a constructor with parameters used to add different values to distinct objects.

Example:

using System;  
   public class Employee  
    {  
        public int emp_id;   
        public String emp_name;  
        public void insert(int x, String y)  
        {  
            emp_id = x;  
            emp_name = y;  
        }  
        public void display()  
        {  
            Console.WriteLine(emp_id + " " + emp_name);  
        }  
   }  
   class Details{  
       public static void Main(string[] args)  
        {  
            Employee e1 = new Employee();  
            Employee e2 = new Employee(); 
            Employee e3 = new Employee(); 
            Employee e4 = new Employee(); 
            Employee e5 = new Employee(); 
            e1.insert(10, "Vishal Gupta");  
            e2.insert(11, "Thomas Edison");  
            e3.insert(12, "Tom Smith");  
            e4.insert(13, "Sunita Wills");  
            e5.insert(14, "David Cruise");  
            e1.display();  
            e2.display(); 
            e3.display(); 
            e4.display(); 
            e5.display(); 
 
        }  
    }

Output:

Explanation:

In the above example, we are creating a parameterized constructor.

Please follow and like us:
Content Protection by DMCA.com