Back to feed
Dev.to
Dev.to
7/19/2026
How C# Compiles yield return Into a State Machine

How C# Compiles yield return Into a State Machine

Original: The Hidden Cost of yield in C#: What the Compiler Doesn't Tell You

Short summary

The article explains how C#'s yield return is implemented by the compiler as a hidden state machine class, not as magical method pausing. Local variables are promoted to heap fields, execution is deferred until enumeration, and each yield becomes a new state. Understanding these mechanics clarifies debugging surprises and helps developers decide when lazy evaluation is an optimization versus a source of complexity.

  • yield return compiles into a hidden iterator class with a state machine
  • Local variables become heap fields; execution is deferred until enumeration
  • One allocation replaces another—useful for memory-constant large reads but not always the right tool

Generated with AI, which can make mistakes.

Is this a good recommendation for you?

Comments

Failed to load comments. Please try again.

Explore more