Doesn't match the correct overload in C #

I have the following program

using System; using System.Collections.Generic; using System.IO; using System.Linq; class Program { public static string Foo<T>(params T[] items) { return "A"; } public static string Foo<T>(IEnumerable<T> items) { return "B"; } static void Main() { List<int> items = new List<int>(){0,1,23}; Console.WriteLine(Foo(items)); Console.WriteLine(Foo("XXX")); } } 

which outputs

 A A 

but not

 B A 

Given that List is a subclass of IEnumerable, why does the general form of params match the previous compiler and give an unexpected answer.

+4
source share
1 answer

When the “best member of a function” part of the specification is called (section 7.5.3.2), the list of parameters in question is in extended form (since the first method is applicable only in extended form). At this point, you are comparing two type calls:

 public static string Foo<T>(T[] items) Foo(new[] { items }); 

and

 public static string Foo<T>(IEnumerable<T> items) Foo(items); 

Converting from List<int>[] to List<int>[] is a "better conversion" than converting from List<T> to IEnumerable<T> , so we don’t get to tie-breaks that would otherwise prefer normal forms over the extended form.

+4
source

Source: https://habr.com/ru/post/1497986/


All Articles