#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;
                }
            }
        }
Advertisements

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

2 Responses to #561 – Using a yield break Statement

  1. Tamas Somogyi says:

    ‘yield break’ has nothing to do with loops. It simply finishes the execution of the function so that it returns no more items. It can also be used in conditional statements like if, else, case or anywhere.

    • Sean says:

      Yes, you’re correct. My other posts on yield return / yield break describe how you can use it outside of loops. The loop here merely indicates that we should continue enumerating items until we hit the yield break. In that case, yield break effectively acts to break control out of the loop by returning from the function.

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

%d bloggers like this: