Reputation: 26943
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?
Upvotes: 0
Views: 196
Reputation: 38079
The second method will be called. It is based on conversion rules for the types:
Read Overload Resolution in the C# Language Specification. Specifically you can look at 7.4.2.3, which talks about how conversion conflicts are resolved.
Upvotes: 3
Reputation: 22719
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.
Upvotes: 4