How does the CLR implement IEnumerable <T> in arrays?

I understand that arrays implement IEnumerable<T> "at runtime". According to the MSDN docs for Array :

Starting with the .NET Framework 2.0, the Array class implements the common interfaces System.Collections.Generic.IList<T> , System.Collections.Generic.ICollection<T> and System.Collections.Generic.IEnumerable<T> . Implementations are provided to arrays at runtime, and as a result, common interfaces are not displayed in the declaration syntax for the Array class.

Of course, this is correct. As you study the source code for Array , you will see that it only implements a non-standard version of IEnumerable .

If you run the code snippet below, you will see that the generic Enumerator type 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 could give some insight into how the CLR implements IEnumerable<T> at runtime? What mechanism does this do? Is something hard-coded in the CLR, or is there something in the Array class that tells the CLR to dynamically implement the generic version?

As a follow-up, I read “C # 5.0 in a nutshell” and on page 274, the authors argue that the Array class must implement a non-generic version of IEnumerable for “backward compatibility”. Can anyone suggest an example of the need for "backward compatibility"?

+6
source share

Source: https://habr.com/ru/post/986580/


All Articles