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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With