Why does IEnumerable inherit from IEnumerable?

Straight from the horse’s mouth (Hejlsberg):

Ideally all of the generic collection interfaces (e.g. ICollection<T>, IList<T>) would inherit from their non-generic counterparts such that generic interface instances could be used both with generic and non-generic code. For example, it would be convenient if an IList<T> could be passed to code that expects an IList.

As it turns out, the only generic interface for which this is possible is IEnumerable<T>, because only IEnumerable<T> is contra-variant: In IEnumerable<T>, the type parameter T is used only in “output” positions (return values) and not in “input” positions (parameters). ICollection<T> and IList<T> use T in both input and output positions, and those interfaces are therefore invariant. (As an aside, they would have been contra-variant if T was used only in input positions, but that doesn’t really matter here.)

<…snip…>

So, to answer your question, IEnumerable<T> inherits from IEnumerable because it can! 🙂

Leave a Comment