Why Arrays implements IEnumerable but does not implement IEnumerableT?

4

I was making a class that contains an Array of class Episode :

public Episode[] EpisodesList;

Then I implemented IEnumerable<T> in my class. And as expected, I implemented the method GetEnumerator() ...

        public IEnumerator<Episode> GetEnumerator()
        {
            return ((IEnumerable<Episode>)this.EpisodesList).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

However, it does not work without casting ...

But just by implementing IEnumerable (without being IEnumerable<T> ), it works normal, without casting :

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.EpisodesList.GetEnumerator();
    }

Why this?

    
asked by anonymous 15.04.2015 / 06:57

1 answer

4

Array definitely implements IEnumerable<T> . Try

bool isIEnumerableGeneric = EpisodesList is IEnumerable<Episode>

and you will see that the result is true .

The reason for the behavior you describe is, as I understood it from documentation , is that the implementation is only "made available" ( provided ) at runtime and so the generic interface does not appear in the "declaration syntax" > of the Array class .

Excerpt from the documentation:

  Starting with the .NET Framework 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable 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 . In addition, 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 add, insert, or remove elements throw NotSupportedException.

That translating into Portuguese is:

  

Starting with the .NET Framework 2.0, the Array class implements the generic interfaces System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable. Implementations are made available to run-time arrays, and as a result, generic interfaces do not appear in Array class declaration syntax . Additionally, there are no referenced topics for interface members that are accessible only by casting an array to a generic interface type (explicit interface implementations). The important thing is to be aware that when you cast an cast from an array to one of these interfaces, members that add, insert, or remove elements throw NotSupportedException.

    
15.04.2015 / 10:58