#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))

            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;
                    yield return next;
                    last = current;
                    current = next;

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: