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.
yield keyword in a method with the return type of
IEnumerator<T> tells the compiler to generate an implementation of the return type (
IEnumerator) that, when looped over, runs the method up to each "yield" to get each result.
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.
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