Phase 12 of 30 · Topic 12.2

`yield return` & `yield break` Compiler State Machines

1Concept

`yield return` causes the Roslyn compiler to synthesize an `IEnumerator<T>` state machine class, maintaining local variables and execution resumption points across iterations.

2Architecture Diagram

Method with `yield return`:
Caller calls MoveNext() ──> State Machine enters State 0 ──> Computes item ──> Pauses & yields
Caller calls MoveNext() ──> State Machine resumes at State 1 ──> Computes next ──> Pauses

3Code Example

C# 13 & .NET 9
using System;
using System.Collections.Generic;

public class YieldDemo
{
    public static IEnumerable<int> GenerateFibonacci(int count)
    {
        int a = 0, b = 1;
        for (int i = 0; i < count; i++)
        {
            yield return a;
            int temp = a + b;
            a = b;
            b = temp;
        }
    }

    public static void Main()
    {
        Console.Write("Fibonacci Sequence: ");
        foreach (int fib in GenerateFibonacci(7))
        {
            Console.Write($"{fib} ");
        }
        Console.WriteLine();
    }
}

4Expected Output

Fibonacci Sequence: 0 1 1 2 3 5 8 

5Key Takeaways

  • `yield return` produces infinite or large streams without high memory allocation.
  • `yield break` immediately terminates sequence generation.
  • Never place `yield return` inside `try-catch` blocks (only `try-finally` is supported).