yield break
C#
programming
iterators
code explanation

What does yield break; do in C?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In C#, the yield break; statement is a control flow statement associated with iterator blocks, which are methods, properties, or accessors that use the yield keyword. Iterators allow you to use the yield return and yield break; statements to control the iteration over collections more flexibly and succinctly within the IEnumerable or IEnumerator interface framework.

What is yield break;?

The yield break; statement is used within an iterator block to end the iteration prematurely. When yield break; is encountered, an iterator method signals the end of iteration. This provides a clean and straightforward way to terminate iteration without needing additional state variables or conditions.

Understanding Iterators in C#

Iterators are especially useful in defining custom iteration behavior on collections. An iterator method can return one of two interfaces: IEnumerable<T> or IEnumerator<T>. Here is a basic format of an iterator utilizing yield return and yield break;:

csharp
1public IEnumerable<int> CustomIterator(int start, int end)
2{
3    for (int i = start; i <= end; i++)
4    {
5        if (i > 10) // Sample condition to break the iteration
6        {
7            yield break;
8        }
9        yield return i;
10    }
11}

How yield break; Works

  1. State Chart Management: When the CustomIterator method is called, it does not immediately execute. Instead, it returns an enumerator, and the body of the iterator executes when the enumerator is iterated over (e.g., by a foreach loop).
  2. Termination of Iteration: The yield break; statement within the iterator allows you to terminate the sequence of yielding results early. Once yield break; is executed, the control exits the method, and any subsequent calls to iterator methods yield no additional results.

Example Usage

Consider the following application of yield break;:

csharp
1static void Main(string[] args)
2{
3    foreach (int number in CustomIterator(5, 15))
4    {
5        Console.WriteLine(number);
6    }
7}

In this example, the CustomIterator method will yield numbers starting from 5 and stop yielding once the number exceeds 10, regardless of the original end parameter value.

Benefits of Using yield break;

  • Simplified Control Flow: Avoids complexity associated with traditional loop variables or multiple exit points in the iterator block.
  • Readability: The intent to terminate iteration early is apparent and explicit.
  • Performance: Reduces unnecessary computations or state checks beyond the point where they become irrelevant in the iteration logic.

Comparison with Traditional Iteration

Below is a table summarizing key differences between using yield break; with iterators and traditional approach:

FeatureIteration with yield break;Traditional Foreach Loop
Code ComplexitySimplifies with less boilerplateMay require flags, counters
Early TerminationUse yield break; to stop immediatelyMust break explicitly inside condition
State ManagementManaged automatically by C# compilerManual state handling
ReadabilityHigh due to clear semanticsCan become convoluted
Resource ConsumptionMinimal, only evaluates as neededPotentially higher, iterates through setup

Additional Considerations

  • Compatibility: The yield break; statement is closely tied to C#'s iterator semantics and is not directly available outside this context.
  • Best Practices: Use yield break; to simplify and enhance clarity, particularly when dealing with large datasets or complex business logic that involves multiple exit points within iteration logic.

Conclusion

The yield break; statement in C# provides a robust mechanism for controlling iteration flow within iterator blocks, offering clear advantages in terms of readability, performance, and code management. It is particularly useful in scenarios that require early termination of the iteration sequence, making your code cleaner and more comprehensible.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.