liveBook · Manning

Iterator method

As explained in C# Concurrency: Asynchronous and multithreaded programming

A C# method associated with yield return that produces a sequence through deferred, resumable execution.

An iterator method produces a sequence through deferred, resumable execution. It starts when iteration requests a value, runs until yield return, suspends, and resumes when the next value is requested. section 2.2

Iterator methods connect ordinary C# sequence consumption to compiler-generated iteration machinery:

  • Return IEnumerable<T>, allowing foreach and other sequence-oriented constructs to consume the result without knowing its implementation. section 2.2
  • Use an enumerator to expose the current value and advance with MoveNext. section 2.2
  • Rely on the compiler to rewrite the method into enumerable and enumerator classes that track execution steps. section 2.2

List versus yield return

A list-building method adds both values before returning. An iterator method can instead declare IEnumerable<int> and yield return 1 and yield return 2; foreach requests each value as needed.

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains deferred execution and compiler-generated enumerable and enumerator state tracking, stopping short of broader performance analysis.
Examples
Compares eager list construction with a two-value yield return method and shows the generated MoveNext state machine.
What it assumes
Assumes familiarity with C# methods and foreach while establishing sequence and enumerator interfaces.
What you can do after
Evaluate/understand iterator execution by relating yield return code to IEnumerable<T>, IEnumerator<T>, and compiler-generated states.
How it connects
Connects yield return with IEnumerable<T>, IEnumerator<T>, foreach, and coroutines.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.