6

Today I discovered something strange. I wonder why this works:

static void Main(string[] args)
{
    Console.WriteLine(ExampleMethod(3));
    Console.ReadKey();
}

public static string ExampleMethod(int required, params int[] optionalint)
{
    return "ExampleMethod 2";
}

public static string ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10) 
{
    return "ExampleMethod 1";
}

Think about it: What is the result when you call ExampleMethod(3);

In my opinion it leads to an unpredictable result. In my case always Method 1 was called. But as I changed the signature of Method 1, the Main Method called Method 2 (of course).

I did not expect such a behavior, I expected an "AmbiguousReferenceException" or at least a compiler warning.

baschdy
  • 103
  • 3
  • Short answer: because the spec says so. http://www.microsoft.com/en-us/download/details.aspx?id=7029 – Tim S. Jun 30 '13 at 12:32

1 Answers1

5

I'd expect this behaviour because the compiler knows the default values of optionalstr and optionalint and is therefore able to make a decision based on that on what values to use. It wouldn't know what to set as the value for int[] optionalint. Since the compiler is "more sure" of what to use when you have the optional parameters, it calls that method.

If you added an extra method like this

public static string ExampleMethod(int required)
{
    return "ExampleMethod 3";
}

this would be the method called because the compiler will go for the method that has no optional parameters first.

More detailed explanation on overload resolution.

Community
  • 1
  • 1
keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • The rules for which overload resolution are pretty detailed. This answer to a similar question has some more info: http://stackoverflow.com/questions/3190248/how-does-c-sharp-choose-with-ambiguity-and-params – Kevin Nacios Jun 30 '13 at 12:28
  • Thanks, I've added the link to the answer. – keyboardP Jun 30 '13 at 12:31
  • aaah, ok that makes sense. Thank you. I didn't think so far, that in one version the parameters were implicitly set. – baschdy Jun 30 '13 at 12:35
  • @baschdy - You're welcome. Kevin has posted a good link with more details on how the compiler resolves overloads. – keyboardP Jun 30 '13 at 12:36