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?
-
Arrayclass, 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), implementsIEnumerable<T>. -
Arrays implement IEnumerable so for any T[] there is a conversion to IEnumerable<T>.
-
from: msdn Array Class
In the .NET Framework version 2.0, the Array class implements the
IList<T>,ICollection<T>, andIEnumerable<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. -
This is a standard interface conversion; as a requirement, arrays (
T[]) implementIEnumerableandIEnumerable<T>. So astring[]is 100% compatible withIEnumerable<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[]toSystem.Collections.Generic.IList<S>and base interfaces of this interface. - From a one-dimensional array-type
S[]toSystem.Collections.Generic.IList<T>and base interfaces of this interface, provided there is an implicit reference conversion fromStoT.
And recall that
IList<T> : IEnumerable<T> - From a one-dimensional array-type
-
how does the implicit conversion string[] -> IEnumerable work?
That kind of misses the point, because there is no conversion. Arrays implement (you could almost say "inherit from", if that makes more sense to you) IEnumerable, and so string[] already is an IEnumerable — there's nothing to convert
0 comments:
Post a Comment