What does 'yield return' do inside a method, and how does it turn an ordinary method into an iterator?
Short answer
'yield return' produces one value at a time from a sequence WITHOUT computing and storing the entire sequence upfront — the method's return type must be IEnumerable (or IEnumerator ), and the compiler transforms it into a state machine that pauses execution at each yield and…
Advertisement
AModel answer
'yield return' produces one value at a time from a sequence WITHOUT computing and storing the entire sequence upfront — the method's return type must be IEnumerable<T> (or IEnumerator<T>), and the compiler transforms it into a state machine that pauses execution at each yield and resumes from there on the next iteration request.
public IEnumerable<int> CountToThree() {
yield return 1;
yield return 2;
yield return 3;
}
foreach (int n in CountToThree()) {
Console.WriteLine(n); // 1, 2, 3
}Real-world example
Lazily generating a sequence of values one at a time instead of building and returning a fully materialized List<T>.
Likely follow-ups
- What does the method's execution state look like BETWEEN successive foreach iterations?
Related topics