Why is a method using 'yield return' considered LAZY, and what does that mean for when its code actually executes?
Short answer
Code inside an iterator method DOESN'T run at all when you first call it — it only executes incrementally, ONE STEP AT A TIME, as the consumer actually requests each next value (via foreach or manual MoveNext() calls) — meaning side effects (like Console.WriteLine) inside the…
Advertisement
AModel answer
Code inside an iterator method DOESN'T run at all when you first call it — it only executes incrementally, ONE STEP AT A TIME, as the consumer actually requests each next value (via foreach or manual MoveNext() calls) — meaning side effects (like Console.WriteLine) inside the method are deferred until iteration actually happens.
public IEnumerable<int> GetNumbers() {
Console.WriteLine("Starting!"); // doesn't print until iteration actually begins
yield return 1;
yield return 2;
}
var numbers = GetNumbers(); // 'Starting!' NOT printed yet
foreach (var n in numbers) { } // NOW 'Starting!' prints, right before yielding 1Real-world example
Understanding why a database query wrapped in a yield-based method doesn't actually execute until you start enumerating its results.
Likely follow-ups
- What happens if you call GetEnumerator() twice on the SAME IEnumerable<T> returned from a yield-based method?
Related topics