Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# method overload with params and optionals

Tags:

c#

.net

params

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.

like image 582
baschdy Avatar asked Jun 30 '13 12:06

baschdy


1 Answers

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.

like image 177
keyboardP Avatar answered Sep 28 '22 09:09

keyboardP