Sobes.tech
Middle+

How does yield work? Why was the yield keyword introduced? How does lazy execution of IEnumerable work?

sobes.tech AI

Answer from AI

The yield keyword in C# is used to create iterators that allow returning elements of a sequence one at a time, without the need to create and store the entire collection in memory at once.

When a method contains yield return, the compiler transforms it into a state machine that returns the next element each time it is called. This enables lazy execution — elements are computed and returned only as needed.

Lazy execution of IEnumerable means that sequence elements are not generated in advance, but only when the iterator is invoked (for example, in a foreach loop). This saves memory and allows working with potentially infinite or very large sequences.

Example:

IEnumerable<int> GetNumbers()
{
    for (int i = 0; i < 5; i++)
    {
        yield return i; // return one element at a time
    }
}

foreach(var num in GetNumbers())
{
    Console.WriteLine(num); // elements are generated as they are iterated
}

Thus, yield simplifies writing iterators and ensures efficient lazy computation of sequences.