yield keyword and lazy evaluation in C#

yield is a new contextual keyword introduced to C# 2.0, vital for lazy evaluation and the performance of queries in LINQ. Being a contextual keyword means that yield can be used as a variable name in C# without any problem. When put before return it becomes a keyword.

yield allows one enumerable class to be implemented in terms of another. This enables the delay of execution of queries until the latest possible moment, skipping the generation of intermediate results that would drastically reduce poerformance. The query operators in LINQ operate on sequence. The result of a query is often another sequence. Lazy evaluation means that until you iterate over the result of the query, the source of the query is not iterated.

To show you how yield works, let’s consider the same class I used in my last post, Winner.

and create a class WinnerDB, that contains a list of UEFA Champion League winners. This class implements IEnumerable and returns an enumerator, WinnerEnumerator, to be able to iterate over the winners.

The usage of this class would look like this:

and the output of the program

So far so good. But with yield, you can let the compiler do all that stuff for you. When you use yield, the compiler generates an enumerator that keeps the current state of the iteration.

Running this code will produce the same output as the previous one, except that the implementation is much simpler. Perhaps the example is not the best, but should give you a hint of the use of the yield keyword. To see that the source is actually iterated only when the result is iterated, we can modify the WinnersDB method to print a message in the console:

In this case, the output looks like this:

1 Reply to “yield keyword and lazy evaluation in C#”

  1. Actually, you do not need to build that array up front and the foreach in the sample, you can just yield return for each new Winner and be even more lazy.


    public static IEnumerable WinnerDB()
    yield return new Winner(“Barcelona”, “Spain”, 2006);
    yield return new Winner(“FC Porto”, “Portugal”, 2004);


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.