Reputation: 27871
It seems that in C#, parameter names can participate in extension methods resolution. Here is an example:
class Program
{
static void Main(string[] args)
{
var x = 1.Do1(b: 1);
var x2 = 1.Do1(c: 1);
Console.WriteLine(x);
Console.WriteLine(x2);
}
}
public static class Ext1
{
public static int Do1(this int a, int b)
{
return 1;
}
}
public static class Ext2
{
public static int Do1(this int a, int c)
{
return 2;
}
}
In this program, the compiler is able to infer that the first call to Do1
is a call to Ext1.Do1
and the second call is to Ext2.Do1
because I specified the names of the arguments.
Is this a documented feature of C#? Where? I was not able to find it.
Upvotes: 1
Views: 86
Reputation: 31
As @Haytam point out, this process is call Overload Resolution. It's described in the Expressions section in the C# language specifications.
First, to find the best overload, the set of all possible overloads must be found, called applicable function members. There is a bunch of rules to find the overloads. As you might guess, the two methods are valid candidates for the method call. But compiler takes the more specific ones base on explicit arguments in your case.
Upvotes: 0
Reputation: 4733
Yes, it's documented in the official Microsoft docs, it's called Overload Resolution.
Although it's a general thing (as in, it applies everywhere), so the results you're getting are normal.
Quote:
Use of named and optional arguments affects overload resolution in the following ways:
A method, indexer, or constructor is a candidate for execution if each of its parameters either is optional or corresponds, by name or by position, to a single argument in the calling statement, and that argument can be converted to the type of the parameter.
If more than one candidate is found, overload resolution rules for preferred conversions are applied to the arguments that are explicitly specified. Omitted arguments for optional parameters are ignored.
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.
Upvotes: 4