Search code examples
c#genericsoverload-resolution

c# overload resolution rules


suppose the following extension methods:

public static string ToFooBarString(this object obj)
{
...
}

public static string ToFooBarString< T >(this IEnumerable< T > obj)
{
...
}

Now i call this over a implementation of the IEnumerable< T > interface, say

Dictionary< int , string > f; // implements IEnumerable< KeyValuePair< int , string > >
f.ToFooBarString(); // <--- which one is called?

which one is called in this case and why?


Solution

  • The compiler chooses the overload "closest" to the type in question. So, it will pick the second overload. (When the compiler can't figure it out, it will complain about it being ambiguous.)

    Since "object" is at the top of the hierarchy, any other applicable overload will be used first.

    More importantly, this can be discovered through testing and through reading of numerous books, online articles, documentation, blogs, etc. A bit of googling should have found it faster than posting here.