Stats

2986 Contributors: 41 Tuesday, April 11, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Yield Keyword

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

  • yield return [TYPE]
  • yield break

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

Related Examples