C# Constructor Overloading

In C#, a constructor is a special type of method that is called automatically when an object of a class is created. It is used to initialize the state of an object by assigning values to the fields or properties of the object.

Constructor overloading is a feature in C# that allows you to define multiple constructors for a class, each with a different signature. This means that you can create objects of a class using different combinations of arguments, and each constructor will initialize the object in a different way.

Why Use Constructor Overloading?

Constructor overloading is useful in situations where you need to create objects of a class with different initial values. For example, consider a Person class with the following fields: name, age, and gender. You can define a constructor that takes all three values as arguments and initializes the object. However, there may be situations where you only have the name and age of a person, and not their gender. In this case, you can define a constructor that takes only the name and age as arguments and sets the gender to a default value.

Constructor Overloading Example

Here's an example of a Person class that has two constructors - one that takes all three fields as arguments, and another that takes only the name and age:

1class Person 2{ 3 public string Name { get; set; } 4 public int Age { get; set; } 5 public string Gender { get; set; } 6 7 // Constructor that takes all three fields as arguments 8 public Person(string name, int age, string gender) 9 { 10 Name = name; 11 Age = age; 12 Gender = gender; 13 } 14 15 // Constructor that takes only name and age as arguments 16 public Person(string name, int age) 17 { 18 Name = name; 19 Age = age; 20 Gender = "Unknown"; 21 } 22}

With these constructors, you can create objects of the Person class in two different ways:

1Person person1 = new Person("William Max", 22, "Male"); 2Person person2 = new Person("Jane Smith", 25);

In the first example, the Person object is initialized with a name, age, and gender. In the second example, the Person object is initialized with only a name and age, and the gender is set to the default value of "Unknown".