How would you implement infinite lazy sequence generation using yield return, and why is this safe despite never 'finishing'?
Short answer
An iterator method can contain an infinite loop (like 'while (true)') that yields indefinitely — this is completely safe because the method only computes ONE value at a time, on demand, whenever the consumer calls MoveNext(); nothing forces the ENTIRE infinite sequence to be…
Advertisement
AModel answer
An iterator method can contain an infinite loop (like 'while (true)') that yields indefinitely — this is completely safe because the method only computes ONE value at a time, on demand, whenever the consumer calls MoveNext(); nothing forces the ENTIRE infinite sequence to be computed unless the consumer explicitly tries to enumerate it all (e.g., calling .ToList() without a Take() first, which WOULD hang forever).
public IEnumerable<int> Fibonacci() {
int a = 0, b = 1;
while (true) { // infinite, but safe due to lazy evaluation
yield return a;
(a, b) = (b, a + b);
}
}
var firstTen = Fibonacci().Take(10).ToList(); // safely gets exactly 10 valuesReal-world example
Generating an infinite sequence (Fibonacci numbers, natural numbers, or a repeating pattern) that's only ever consumed a finite amount at a time.
Likely follow-ups
- What would happen if you accidentally called .ToList() directly on this infinite Fibonacci() sequence without a preceding Take()?
Related topics