views:

75

answers:

2
    public ClassType(string type) {
        Type = type;
    }
    public ClassType(string type,bool isArray=false) {
        Type = type;
        IsArray = isArray;
    }


    ClassType ct = new ClassType("adsf");

Which constructor is chosen?

+7  A: 

The overload that doesn't require an optional parameter. Note that it's just a "yes" or "no" decision here: "no optional parameters filled in automatically" is preferable to "some optional parameters filled in automatically" but there's no preference between 1 or 2 being filled in. (That would be ambiguous.)

From section 7.5.3.2 of the C# 4 spec:

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.

Jon Skeet
Which raises the question, "Why isn't that a compile time error?" (I'm pretty sure it is in C++, and C# gives errors for a lot more edge cases that C++ lets by.)
James Curran
@James: There's a method which exactly matches the arguments you've given, so I guess it's deemed to be fine. I suspect it makes it easier to add optional parameters to existing types.
Jon Skeet
BTW: I've just ported that code to VC++ and confirmed that with that compiler at least, it is an error. I think the C++98 Standard makes it always an error. Odd that C# lets it pass. I guess it's to allow you to turn previously required parameters into optional params, but in that case you'd really want to know if you created an ambigity.
James Curran
+1  A: 

As Jon said, in two words, the first one. The match is 'cleaner'.

Mau
Isn't "the first one" three words, not two? ;)
Jon Skeet
Yes, but 'in three words' sounds less cool :-)
Mau