C# Yield

Deferred Execution

From docs.microsoft.com

Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. Deferred execution can greatly improve performance when you have to manipulate large data collections, especially in programs that contain a series of chained queries or manipulations. In the best case, deferred execution enables only a single iteration through the source collection.

The LINQ technologies make extensive use of deferred execution in both the members of core System.Linq classes and in the extension methods in the various LINQ namespaces, such as System.Xml.Linq.Extensions.

Deferred execution is supported directly in the C# language by the yield keyword (in the form of the yield-return statement) when used within an iterator block. Such an iterator must return a collection of type IEnumerator or IEnumerator (or a derived type).

Code Example

Not sure about real world application but this is a code example based on a post from stack overflow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class YieldDemo
{
public YieldDemo()
{
var doTheYieldThing = new DoTheYieldThing();

var infiniteOnes = doTheYieldThing.InfiniteOnes();

var counter = 1;
foreach (var one in infiniteOnes.Take(10))
{
Console.WriteLine("one={0}, counter={1}", one, counter);
counter++;
}

Console.WriteLine("----------------------------");

foreach (var one in infiniteOnes.Take(10))
{
Console.WriteLine("one={0}, counter={1}", one, counter);
counter++;
}
}
}

public class DoTheYieldThing
{
public IEnumerable<int> InfiniteOnes()
{
while (true)
yield return 1;
}
}

This results in

Yield

References