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.
