what is ‘this’ constructor, what is it for

It’s used to refer to another constructor in the same class. You use it to “inherit” another constructor:

public MyClass() {}

public MyClass(string something) : this() {}

In the above, when the second constructor is invoked, it executes the parameterless constructor first, before executing itself. Note that using : this() is the equivalent of : base(), except it refers to a constructor in the same class, instead of the parent class.

There’s an article about constructors here (MSDN), which provides a usage example:

public Employee(int annualSalary)
{
    salary = annualSalary;
}

public Employee(int weeklySalary, int numberOfWeeks)
    : this(weeklySalary * numberOfWeeks)
{
}

Leave a Comment