#561 – Using a yield break Statement
April 13, 2012 2 Comments
When implementing an iterator, the 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; } } }
‘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.
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.