Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should an iterator return an IEnumerator instead of an IEnumerable?

Using yield return turns a method into an iterator. The return type of an iterator must be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.

I have found that an iterator can only be used in a foreach loop if it returns one of the IEnumerable types. Given this limitation, when would it make sense to choose an IEnumerator return type instead of an IEnumerable?

like image 555
user200783 Avatar asked Apr 15 '20 12:04

user200783


1 Answers

Pretty rarely, to be honest. The only times I've seen it used that way is when special-casing things for some reason in the GetEnumerator() method (before firing up the iterator block machinery), but still wanting an iterator block for the actual implementation, i.e.

public IEnumerator<T> GetEnumerator()
{
    if (someScenario) return SomethingSpecialPerhapsEmptyArrayEnumerator();
    if (anotherScenario) ThrowSomeException();
    return DoTheThing();
}
private IEnumerator<T> DoTheThing()
{
    // ... yield return
}
like image 194
Marc Gravell Avatar answered Oct 27 '22 00:10

Marc Gravell