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?
Like all functions, a constructor can have default arguments. They are used to initialize member objects. If default values are supplied, the trailing arguments can be omitted in the expression list of the constructor.
In Java, we can overload constructors like methods. The constructor overloading can be defined as the concept of having more than one constructor with different parameters so that every constructor can perform a different task.
There are no parameters accepted by default constructors. The compiler will give an implicit default constructor if the programmer does not explicitly provide one. In that scenario, the variables' default values are 0.
Constructor overloading in Java refers to the use of more than one constructor in an instance class. However, each overloaded constructor must have different signatures. For the compilation to be successful, each constructor must contain a different list of arguments.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With