Which C# method overload is chosen?

Overloads are resolved by choosing the most specific overload. In this case, method1<string>(string) is more specific than method1(object) so that is the overload chosen.

There are details in section 7.4.2 of the C# specification.

If you want to select a specific overload, you can do so by explicitly casting the parameters to the types that you want. The following will call the method1(object) overload instead of the generic one:

method1((object)"xyz"); 

There are cases where the compiler won't know which overload to select, for example:

void method2(string x, object y);
void method2(object x, string y);

method2("xyz", "abc");

In this case the compiler doesn't know which overload to pick, because neither overload is clearly better than the other (it doesn't know which string to implicitly downcast to object). So it will emit a compiler error.


C# will always choose the most specific method it can.

When compiling

method1("xyz");

it will look for all methods with the specified name and then attempt to match parameters. The compiler will choose the method that is the most specific, in this case it would prefer

method1(string s)

over

method1<T>(T t) with T = string

and lastly

method1(object o)

Please note @Erik's excellent answer for an example where the compiler fails to decide.

Tags:

C#

.Net

Generics