Yagzii
Yagzii

Reputation: 286

Resolving Ambiguities with Optional Parameters and Named Arguments

I have two methods on my project as defined below:

void Person(int ID, double height = 0.0, string team = "Knights")
{
   //my codes
}
void Person(int ID, double height = 0.0, string team = "Knights", int age = 30)
{
   //my codes
}

This is where I'm calling the method:

Person(1, 2.5, "Dark Ghost"); //calls first method

I didn't get any error when I built the project however I'm confused why above calls the first method?

and :

Person(1, 46.5);   //compiler error. 

Upvotes: 2

Views: 929

Answers (3)

Kendall Frey
Kendall Frey

Reputation: 44374

The C# specification says in §7.5.3.2, regarding choosing a better overload:

If all parameters of [Method A] have a corresponding argument whereas default arguments need to be substituted for at least one optional parameter in [Method B] then [Method A] is better than [Method B].

When you specify a value for all parameters:

Person(1, 2.5, "Dark Ghost");

The above rule makes the first method a better candidate, and it is chosen as the correct overload.

When you don't:

Person(1, 46.5);

The rule does not apply, and the overload resolution is ambiguous.


You might say, why not choose the one with the least parameters? That seems fine at first, but causes a problem when you have something like this:

void Foobar(int a, string b = "foobar")
{
}

void Foobar(int a, int b = 0, int c = 42)
{
}

...

Foobar(1);

In this case there's no valid reason to choose the first one over the second. Thus you can only properly resolve this by supplying a value for all parameters.

Upvotes: 3

Andrea Scarcella
Andrea Scarcella

Reputation: 3333

TL:DR The first method (most specific) will be called because in that case no parameter needs to be bound using default values.

For an in-depth discussion refer to this article.

Upvotes: 0

daryal
daryal

Reputation: 14929

If possible, the one which can be applied without default parameters is called.

In the first case

Person(1, 2.5, "Dark Ghost");

First method is called.

In the second case:

Person(1, 46.5);

It will simply result in build error. "The call is ambiguous between the following methods or properties: Test.Person(int, double, string) and Person(int, double, string, int)".

Upvotes: 1

Related Questions