C# Language Yield Keyword

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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



Got any C# Language Question?