.NET Why can string [] be passed as an IEnumerable <string> parameter?

This is a valid code:

void func(IEnumerable<string> strings){ foreach(string s in strings){ Console.WriteLine(s); } } string[] ss = new string[]{"asdf", "fdsa"}; func(ss); 

What I want to know how the implicit conversion of string[] -> IEnumerable<string> works?

+4
source share
5 answers

from: msdn array class

In the .NET Framework version 2.0, the Array class implements

  • IList<T> ,
  • ICollection<T> and
  • IEnumerable<T>

common interfaces. Implementations are provided to arrays at runtime and therefore are not visible to documentation assembly tools. As a result, common interfaces are not displayed in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array into a common interface type (explicit interface implementations). The key value to consider when creating an array on one of these interfaces is the elements that add, insert, or delete throw NotSupportedException elements.

+12
source

Array class, which is a very strange beast and is very carefully handled by the compiler and JIT (more about this in Richter and Don Box books), implements IEnumerable<T> .

+5
source

Arrays implement IEnumerable, so for any T [], a conversion to IEnumerable <T> occurs.

+3
source

how does the implicit conversion string [] → IEnumerable work?

This kind of misses item because there is no conversion. Implementation arrays (you could say almost “inherit from” if that makes sense to you) are IEnumerable, and so the string [] is already IEnumerable - there’s nothing to convert

+2
source

This is a standard interface conversion; as a requirement, arrays ( T[] ) implement IEnumerable and IEnumerable<T> . Thus, string[] is 100% compatible with IEnumerable<T> . Implementation is provided by the compiler (arrays were mostly generic before .NET files were distributed).

From the specification (ECMA 334 v4) - this is a consequence of 13.1.4:

  • From the one-dimensional array S[] to System.Collections.Generic.IList<S> and the base interfaces of this interface.
  • From the one-dimensional array S[] to System.Collections.Generic.IList<T> and the base interfaces of this interface, provided that there is an implicit reference conversion from S to T

And remember that IList<T> : IEnumerable<T>

0
source

All Articles