I accidentally overloaded a constructor in C# as follows:
public MyClass(string myString)
{
// Some code goes here
}
public MyClass(string myString, bool myParameter = false)
{
// Some different code here
}
With this code my project compiled fine. If I call the constructor with just a string
argument, how does C# decide which constructor I want to use? Why is this functionality syntactically allowed?
Why is this functionality syntactically allowed?
In terms of the IL generated, the second constructor is still two arguments. The only difference is that the second argument has an attribute providing the default value.
As far as the compiler is concerned, the first is still technically a better fit when you call a constructor with a single string. When you call this with a single argument, the best match is the first constructor, and the second will not get called.
The C# specification spells this out. In 7.5, it states "... instance constructors employ overload resolution to determine which of a candidate set of function members to invoke." The specific rules are then specified in 7.5.3.2, where this specific rule applies:
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.
In this case, MP (your first constructor) has all arguments, but MQ (your second) needs "at least one optional parameter."