The yield keyword is a neat, but infrequently used, language feature of c#. Essentially, it allows you to “queue-up” results to be returned by a method as an enumerable collection.
Consider this simple example that produces a collection of integers from 0 to 9:
static IEnumerable<int> GetValues() { var result = new List<int>(); for (var i = 0; i < 10; i++) { result.Add(i); } return result; }
By using yield, we can skip the step of creating a List<int> variable to store our results. This function will produce the same result:
static IEnumerable<int> GetValuesYieldEdition() { for (var i = 0; i < 10; i++) { yield return i; } }