yield break and Early Termination
Stop iteration conditionally.
Stopping an Iterator Early
Sometimes you want an iterator to stop producing values before reaching the natural end. The yield break statement ends the sequence immediately, like a return for iterators.
Basic yield break
yield break terminates the iterator. No further values are produced and the foreach loop consuming it ends.
using System;
using System.Collections.Generic;
public class Program
{
static IEnumerable<int> UpToFive()
{
for (int i = 1; i <= 100; i++)
{
if (i > 5) yield break;
yield return i;
}
}
public static void Main()
{
foreach (var n in UpToFive())
Console.WriteLine(n);
}
}All lessons in this course
- Iterator Methods with yield return
- yield break and Early Termination
- Lazy Evaluation Semantics
- Custom Enumerables