When implementing an iterator, what's the difference between returning IEnumerator or IEnumerable?

When implementing an iterator with yield return there a difference between returning IEnumerator and IEnumerable ?

+4
source share
3 answers

IEnumerable and IEnumerator are two different things.

IEnumerable<T> is a sequence that can be repeated.

IEnumerator<T> is the object returned by IEnumerable<T> to repeat the sequence in sequence.

In general, the only place to return IEnumerator<T> is the GetEnumerator() method.

yield return behaves the same for both types, except that the iterator method that returns IEnumerable<T> can be executed several times (each time the sequence is enumerated).
For more information on how this works, see John Skeet's article .

+9
source

As an executor of an iterator function, this does not affect you. This is important for the consumer of the iterator function.

In general, people prefer to have an IEnumerable<T> object, because you can make a foreach loop on it, and if you really need an IEnumerator<T> object, you can get it from the IEnumerable<T> GetEnumerator() object.

+1
source

As SLaks mentioned, Enumerator can be repeated once, and IEnumerable can generate any number of Enumerators, allowing you to iterate through the base collection several times.

In practice, the main difference is that there are many ways, such as LINQ, and many methods for interacting with collections that deal with Enumerables rather than Enumerators, so Enumerator simply cannot be as widely used.

0
source

Source: https://habr.com/ru/post/1397832/


All Articles