0

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?

lurscher
  • 25,930
  • 29
  • 122
  • 185

2 Answers2

4

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.

John Fisher
  • 22,355
  • 2
  • 39
  • 64
  • I think i know what you mean, but is there a rigurous meaning for 'closeness'? – lurscher Apr 27 '12 at 17:14
  • 1
    Tries classes that are most below in the inheritance hierarchy first. – SimpleVar Apr 27 '12 at 17:15
  • so if i would have add another generic overload for say, `ICollection< T >` (which is also implemented by `Dictionary`, then the compiler would have to complain about ambiguity right? – lurscher Apr 27 '12 at 17:17
  • @lurscher: Personally, I think it would be much faster to try it than to ask here. – John Fisher Apr 27 '12 at 17:21
  • 3
    @lurscher: Is there a rigorous meaning for 'closeness'? Yes. **Read the specification.** Specifically you want the section that defines the meaning of "better conversion from type". If you added an extension method that took `ICollection` would it be ambiguous? No. `ICollection` is *more specific* than either `object` or `IEnumerable` and hence a *better conversion* from the dictionary type. – Eric Lippert Apr 27 '12 at 17:29
3

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.

John Koerner
  • 37,428
  • 8
  • 84
  • 134