C# Constructor Overloading

www.‮tfigi‬idea.com

In C#, constructor overloading is a feature that allows you to define multiple constructors with the same name in the same class, but with different parameters. This means that you can have multiple constructors with the same name, but with different input parameters or parameter types, and the appropriate constructor will be called based on the arguments provided.

Here's an example:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person()
    {
        // default constructor
        Name = "Unknown";
        Age = 0;
    }

    public Person(string name)
    {
        // constructor with one parameter
        Name = name;
        Age = 0;
    }

    public Person(string name, int age)
    {
        // constructor with two parameters
        Name = name;
        Age = age;
    }
}

In this example, the Person class defines three different constructors with the same name, but with different parameter types. The first constructor is the default constructor, which sets the Name and Age properties to default values. The second constructor takes one string parameter and sets the Name property to the provided value, and the Age property to the default value. The third constructor takes two parameters, a string and an int, and sets the Name and Age properties to the provided values.

You can create an object of the Person class using any of these constructors. For example:

Person person1 = new Person();
Person person2 = new Person("John");
Person person3 = new Person("Jane", 30);

In this example, person1 is created using the default constructor, person2 is created using the constructor with one parameter, and person3 is created using the constructor with two parameters.

Constructor overloading can make your code more flexible and easier to use, since you can create objects using different combinations of constructor parameters. However, it's important to use constructor overloading sparingly and to make sure that your constructors are clear and easy to understand.