Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why was GetEnumerator() stored in a separate interface from IEnumerator?

I was wondering why the GetEnumerator() method was factored out of IEnumerator and placed in IEnumerable. It seems to me that it would make more sense to keep all of the enumerator methods in IEnumerator.

Thanks,

Scott

like image 491
Scott Davies Avatar asked Jan 02 '10 22:01

Scott Davies


3 Answers

Ask yourself "imagine if this were true".

If all the enumeration methods were on a single interface, how could two callers enumerate the same list at the same time?

There are two interfaces because one says, "You can enumerate me," while the other says, "here's an object that keeps track of a given enumeration task."

The IEnumerable interface is a factory that creates as many IEnumerator objects as you want. How and when those enumerators get used is up to the consumer.

like image 58
Eilon Avatar answered Nov 08 '22 20:11

Eilon


IEnumerable implies that the object is a collection or source of data which can be iterated over in a linear fashion. IEnumerator is the interface for the actual implementation which performs the iteration.

like image 41
Rob Avatar answered Nov 08 '22 21:11

Rob


Because "IEnumerable" says "come, enumerate me" (and then you say- how, give me the Enumerator), however "IEnumerator" says "I can enumerate your collection!" and you already have it, you don't need to get any more.

like image 4
naivists Avatar answered Nov 08 '22 22:11

naivists