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

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

c# 4.0 - Conflicting overloaded methods with optional parameters

I have two overloaded methods, one with an optional parameter.

void foo(string a)  { }  
void foo(string a, int b = 0) { }  

now I call:

 foo("abc");

interestingly the first overload is called. why not the second overload with optional value set to zero?

To be honest, I would have expect the compiler to bring an error, at least a warning to avoid unintentional execution of the wrong method.

What's the reason for this behaviour? Why did the C# team define it that way?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

From MSDN:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...