0Pricing
C# Academy · Lesson

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

  1. Iterator Methods with yield return
  2. yield break and Early Termination
  3. Lazy Evaluation Semantics
  4. Custom Enumerables
← Back to C# Academy