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
?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With