Why does Arrays implement Ienumerable but not Ienumerable<T>?

Asked

Viewed 122 times

4

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

public Episode[] EpisodesList;

Then I implemented the 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 the casting...

But only by implementing the IEnumerable (other than the IEnumerable<T>), works normal without casting:

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

Why is that?

1 answer

4


Array definitely implements IEnumerable<T>. Try making

bool isIEnumerableGeneric = EpisodesList is IEnumerable<Episode>

and you’ll see that the result is true.

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

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 which add, Insert, or remove Elements throw Notsupportedexception.

What translating into Portuguese is:

From 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 for runtime arrays, and as a result, generic interfaces do not appear in the Array class declaration syntax. Additionally, there are no topics referenced for interface members that are accessible only when performing cast of an array for a generic interface type (explicit interface implementations). The important thing is to be aware that when you perform the cast from an array to one of these interfaces is that memebros that add, insert, or remove elements launch Notsupportedexception.

  • I took the liberty of adding a translation of the excerpt in English, if you don’t mind.

  • Not at all. So it became more complete.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.