X

C# constructor overloading

dotnet C#

In C# if one wishes to use C# constructor overloading they can use the “this” keyword right after to initialize the object, the only thing to note is one will not be able to do any validation of the data using this method.

Below I have listed 3 ways that one can initialize constructor overload in C#. There is also a base keyword that one can use to call the base class in their constructor initialization code


//initialize without checking, use the this keyword
public Person(Person p) : this(p.Name, p.Age) { }

//provide a method to initialize
public Person(string name, int age)
{    
    Initialize(name, age);
}

//validate the input 
public Person(Person p)
{
    if (p == null)
        throw new ArgumentNullException("p");

    Initialize(p.Name, p.Age);
}

private void Initialize(string name, int age)
{
    Name = name;
    Age = age;
}

//initialize the base class
public Person(string name, int age): base(name, age) { }
Categories: .NET C#
Taswar Bhatti:
Related Post