6

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>, and System.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"?

Tom Baxter
  • 2,110
  • 2
  • 19
  • 38
  • 2
    Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). – John Saunders May 05 '15 at 15:08
  • 2
    I don't have documentation to cite but I'm pretty sure it will be hard-coded into the CLI to handle Array as a special case. – James May 05 '15 at 15:11
  • 2
    Check out http://stackoverflow.com/questions/4489661/whats-the-magic-of-arrays-in-c-sharp which may be even considered duplicate of your question. – Alexei Levenkov May 05 '15 at 15:13
  • 1
    It comes with the implementation of `IList` http://stackoverflow.com/questions/11163297/how-do-arrays-in-c-sharp-partially-implement-ilistt – Matthew Watson May 05 '15 at 15:34

0 Answers0