views:

457

answers:

5

This is 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 is, how does the implicit conversion string[] -> IEnumerable<string> work?

+5  A: 

Array class, which is a very strange beast and is treated very specially by the compiler and JIT (more on that in Richter's and Don Box's books, I guess), implements IEnumerable<T>.

Anton Gogolev
+3  A: 

Arrays implement IEnumerable so for any T[] there is a conversion to IEnumerable<T>.

JaredPar
+10  A: 

from: msdn Array Class

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

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

generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear 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 to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.

Daren Thomas
A: 

This is a standard interface conversion; as a requirement, arrays (T[]) implement IEnumerable and IEnumerable<T>. So a string[] is 100% compatible with IEnumerable<T>. The implementation is provided by the compiler (arrays were basically generic before .NET generics existed).

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

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

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

Marc Gravell
+1  A: 
Joel Coehoorn