Yield Keyword

suggest change

Introduction

When you use the yield keyword in a statement, you indicate that the method, operator, or get accessor in which it appears is an iterator. Using yield to define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration) when you implement the IEnumerable and IEnumerator pattern for a custom collection type.

Syntax

Remarks

Putting the yield keyword in a method with the return type of IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T> tells the compiler to generate an implementation of the return type (IEnumerable or IEnumerator) that, when looped over, runs the method up to each “yield” to get each result.

The yield keyword is useful when you want to return “the next” element of a theoretically unlimited sequence, so calculating the entire sequence beforehand would be impossible, or when calculating the complete sequence of values before returning would lead to an undesirable pause for the user.

yield break can also be used to terminate the sequence at any time.

As the yield keyword requires an iterator interface type as the return type, such as IEnumerable<T>, you cannot use this in an async method as this returns a Task<IEnumerable<T>> object.

Further reading

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents