C#advanceddotnet
Iterators with yield
An iterator method that hands back one value at a time with yield return, building a lazy IEnumerable<T> the runtime resumes on demand instead of materialising a list.
yield return produces the next element and parks the method until MoveNext asks again; yield break ends the sequence early, so a foreach can consume an infinite stream and stop after Take(n).
A range iterator
C#intro0ms
5678
Reference · output compiled offline, not runnable in-browser
Each yield return start + i hands back one value (5 through 8) and parks the loop until foreach calls MoveNext again, so the four numbers are produced lazily rather than from a pre-built list. This is the minimal shape of an iterator method: a normal for loop whose yield return the compiler turns into a resumable state machine.