Is IEnumerable<T> an Interface or a Collection?

  • A+

As far as I understand, Interfaces are contracts that implementers must follow. But in that case :

IEnumerable<int> numQuery = numbers.Where(num => num % 2 == 0).OrderBy(n => n); 

IEnumerable is used as a collection type doesn't it ? Why not doing something like this ?

public class EnumCollection<T> : IEnumerable<T> { } EnumCollection<T> numQuery = numbers.Where(num => num % 2 == 0).OrderBy(n => n); 

I think I've missed something...


IEnumerable<T> is an interface that represents a sequence. Now; collections can usually be used as sequences (so... List<T> implements IEnumerable<T>), but the reverse is not necessarily true. In fact, it isn't strictly required that you can even iterate a sequence (IEnumerable<T>) more than once.

Many LINQ operations check whether the sequence you're working with is also a collection (IList<T> etc), in order to provide optimized implementations (.Count rather than counting by iterating, etc).

The result of .Where(...) etc is just: a sequence. It isn't cast back to an EnumCollection<T> just because you started with an EnumCollection<T>. In the case of .Where, the data isn't even stored anywhere - it is a filter that applies the condition while enumerating. Meaning: when you try to fetch the next item, it simply iterates the inner sequence, discarding the items that don't match. In the case of OrderBy it is buffered (by necessity - in the general case, it is impossible to sort without buffering), but: that's an implementation detail that you aren't usually exposed to.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: