user200783
user200783

Reputation: 14348

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?

Upvotes: 5

Views: 431

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063338

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
}

Upvotes: 5

Related Questions