Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# allow quasi-clashing method signatures? [duplicate]

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?

like image 701
Thomas Avatar asked Nov 23 '22 14:11

Thomas


1 Answers

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.

like image 140
Dean Harding Avatar answered Dec 05 '22 06:12

Dean Harding