Search code examples
c#constructoroverloading

Passing default value in constructor


I have a class Executive with the following code for that class:

public class Executive
{
    public Executive(int Id = 0)
    {
        // Constructor 1
        this.BaseSalary = 3000;
        Console.Write("DONE");
    }
    
    public Executive()
    {
        // Constructor 2
        Console.Write("done");
    }
}

And in main I do the following:

Executive exec = new Executive()

It always calls Constructor 2.
Why doesn't it call Constructor 1 (since Id has a default value)?


Solution

  • That's how determining best method to call is done. Optional parameters without specified values are removed from arguments list when overload resolution is performed:

    7.5.3.2 Better function member

    For the purposes of determining the better function member, a stripped-down argument list A is constructed containing just the argument expressions themselves in the order they appear in the original argument list. Parameter lists for each of the candidate function members are constructed in the following way:

    • The expanded form is used if the function member was applicable only in the expanded form.

    Optional parameters with no corresponding arguments are removed from the parameter list

    • The parameters are reordered so that they occur at the same position as the corresponding argument in the argument list.

    Also later in the same paragraph:

    In case the parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are equivalent (i.e. each Pi has an identity conversion to the corresponding Qi), the following tie-breaking rules are applied, in order, to determine the better function member.

    • If MP is a non-generic method and MQ is a generic method, then MP is better than MQ.

    • Otherwise, if MP is applicable in its normal form and MQ has a params array and is applicable only in its expanded form, then MP is better than MQ.

    • Otherwise, if MP has more declared parameters than MQ, then MP is better than MQ. This can occur if both methods have params arrays and are applicable only in their expanded forms.

    Otherwise if all parameters of MP have a corresponding argument whereas default arguments need to be substituted for at least one optional parameter in MQ then MP is better than MQ.

    Which means that if you have two methods that both have applicable parameters but one requires to use optional parameter value and the other one doesn't, the one without optional value is better.