How does 'yield break' work, and how does it differ from a plain 'return' statement inside a regular method?
Short answer
'yield break' immediately stops the iterator's sequence, signaling there are no more elements — it's the iterator equivalent of 'return' in a regular method, but specifically for terminating a lazy sequence early rather than producing a single return value.
Advertisement
AModel answer
'yield break' immediately stops the iterator's sequence, signaling there are no more elements — it's the iterator equivalent of 'return' in a regular method, but specifically for terminating a lazy sequence early rather than producing a single return value.
public IEnumerable<int> TakeWhilePositive(IEnumerable<int> source) {
foreach (int n in source) {
if (n < 0) yield break; // stop the sequence entirely once a negative number is found
yield return n;
}
}
var result = TakeWhilePositive(new[] { 1, 2, -1, 3 }); // yields 1, 2, then stopsReal-world example
Building a custom lazy filtering/limiting operator similar to LINQ's TakeWhile(), stopping the sequence early based on a condition.
Likely follow-ups
- Can you combine 'yield break' with a try/finally block to ensure cleanup runs even when the sequence stops early?
Related topics