Iterators & yield in C#
Implement IEnumerable<T> with yield return and yield break, create lazy sequences, and understand how the C# iterator state machine works.
Why Iterators Matter
1. What is an Iterator?
An iterator produces values one at a time — only when the consumer asks.
The Iteration Protocol
1. IEnumerable<T> and IEnumerator<T>
Any type implementing `IEnumerable<T>` can be used in a `foreach` loop.
2. Built-in Iterables
Arrays, List, Dictionary, string, Range — all implement IEnumerable.
yield return
1. Basic yield return
A method with `yield return` is a generator — it produces values lazily.
2. Generator State Control
The generator remembers local variables across yield returns.
yield break
1. Early Termination with yield break
`yield break` stops the generator — equivalent to `return` in a regular method.
Custom Iterable Class
1. Implementing IEnumerable<T> with yield
Return `IEnumerable<T>` from `GetEnumerator()` using yield — no manual enumerator class needed.
Lazy Evaluation
1. Infinite Sequence with yield
Generators can be infinite — they only compute values when consumed.
Backend Use Cases
1. Batch Processing
Stream large datasets in batches using yield — avoids out-of-memory errors.
Pitfalls & Best Practices
1. Recommended Guidelines
Key rules for writing safe, efficient iterator methods.