1

Why do I need IEnumerable as an abstraction other than "that's the way it was designed" and everything is expecting IEnumerable in their signature? Couldn't they have started with IEnumerator and never made IEnumerable?

I have read various SO questions, but I am still not sure of the answer. It seems to be historical in nature. I am not asking how anything works per se or how to iterate things. I am only asking why IEnumerable exists instead of only IEnumerator. Why does the abstraction of IEnumerable exist?

Why implement IEnumerable(T) if I can just define ONE GetEnumerator?

Why can't I use the enumerator of an array, instead of implementing it myself?

Can anyone explain IEnumerable and IEnumerator to me?

johnny
  • 19,272
  • 52
  • 157
  • 259

1 Answers1

3

Couldn't they have started with IEnumerator and never made IEnumerable?

No. Each call to GetEnumerator() is intended to be independent, i.e.

var iter1 = obj.GetEnumerator();
var iter2 = obj.GetEnumerator();
// now iter1 and iter2 can be advanced separately and
// have nothing to do with each-other, usually

In almost all cases, these separate calls to GetEnumerator() would be from different call locations or possibly different threads, but: they would report separately. The IEnumerable[<T>] API just advertises "has the GetEnumerator() method". If there was only one interface here, then when an object "is" (i.e. implements that interface), it would have no choice but the conflict - you would never be able to obtain separate enumerators over the same data.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • My guess would be that they're confused that `foreach` still works without implementing `IEnumerable` and instead can call a matching `GetEnumerator` method without that method coming from an interface. But that's more an elaborate guess what they could be confused about and if so, they worded that very poorly. – Joey Aug 14 '19 at 09:08