I realize that arrays implement IEnumerable<T>
"at run time". According to the MSDN docs for Array:
Starting with the .NET Framework 2.0, the Array class implements the
System.Collections.Generic.IList<T>
,System.Collections.Generic.ICollection<T>
, andSystem.Collections.Generic.IEnumerable<T>
generic interfaces. The implementations are provided to arrays at run time, and as a result, the generic interfaces do not appear in the declaration syntax for the Array class.
Of course, this is correct. In looking at the source code for Array
you'll see it implements the non-generic version of IEnumerable
only.
If you run the below snippet of code you will see the type of the generic Enumerator
is of type System.SZArrayHelper+SZGenericArrayEnumerator`1[System.String]
.
String[] array = new[] { "Apple", "Banana", "Grape" };
IEnumerator enumer = ((IEnumerable<String>)array).GetEnumerator();
// Next line writes: System.SZArrayHelper+SZGenericArrayEnumerator`1[System.String]
Console.WriteLine(enumer.GetType());
I was hoping someone might be able to provide some insight as to how the CLR implements IEnumerable<T>
at run time? What's the mechanism that makes it happen? Is something hard-coded in the CLR or is there something in the Array
class that informs the CLR to dynamically implement the generic version?
As a follow up, I was reading "C# 5,0 in a Nutshell" and on page 274 the authors claim that the Array
class must implement the non-generic version of IEnumerable
for "backward compatibility". Could someone offer an example of the necessity this for "backward compatibility"?