#561 – Using a yield break Statement

When implementing an iteratorthe yield return statement returns the next element in the sequence being returned.  If you are using a loop within the iterator block, you can use the yield break statement to break out of the loop, indicating that no more elements are to be returned.

In the example below, an iterator is used to return a portion of the Fibonacci sequence.  yield break is used to break out of the loop generating the sequence.

        static void Main()
        {
            // Return Fibonacci numbers below 2,000
            foreach (int i in Fibonacci(2000))
                Console.WriteLine(i);

            int gi = 12;
        }

        private static IEnumerable<int> Fibonacci(int maxValue)
        {
            yield return 0;
            yield return 1;

            int last = 0;
            int current = 1;

            while (true)
            {
                int next = last + current;
                if (next > maxValue)
                    yield break;
                else
                {
                    yield return next;
                    last = current;
                    current = next;
                }
            }
        }