Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
395 views
Welcome To Ask or Share your Answers For Others

1 Answer

From MSDN: (emphasis added)

If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...