Updated on

The yield break statement ends an iterator method on the spot. The sequence stops, and nothing after it in the method runs except a finally block.

Think of it as the iterator’s version of a plain return;, which the compiler doesn’t allow inside an iterator. In the examples that follow, we try it next to break and return and compare what happens.

To download the source code for this article, you can visit our GitHub repository.

So let’s get going.

Iterator Methods in C#

Before discussing yield break, we must understand the concept of iterator methods in C#.

An iterator method defines how to generate elements in the sequence and return them one by one. When we place a yield statement inside a method, the compiler treats that method as an iterator method, and its body as an iterator block.  An iterator method can return different types like IEnumerable, IEnumerator, IEnumerable<T>, or IEnumerator<T>, and IAsyncEnumerable<T> for async streams. It uses the yield return statement to return elements, one by one.

From a compiler’s perspective, it treats an iterator method differently from a regular method, which we are going to see in this article. That said, we have already explained how to use the yield return statement to iterate over a collection and return the elements.  So in this article, we are going to focus on the functionality of the yield break statement.

What Does yield break Do in C#?

yield break ends the iteration and exits the iterator block. Microsoft Learn’s yield reference sums up its job as a way “to explicitly signal the end of iteration”.

Once the iterator reaches yield break, the caller’s foreach loop gets no more elements and finishes. Nothing after it in the method runs except a finally block. When the compiler can prove a statement is unreachable, it raises warning CS0162.

An iterator doesn’t need yield break to finish. Reaching the closing brace of the method ends the iteration too. We use yield break when we want to stop early, for instance when a condition is met or after a set number of items.

A method whose only statement is yield break; is still an iterator, and it returns an empty sequence. That’s a handy way to return “nothing” from a method that has to stay an iterator.

First, let’s create a console app with a Utility class and a method that generates random years from 1900 to 2022:

namespace YieldBreakInCSharp;

public static class Utility
{
    public static IEnumerable<int> GenerateRandomYears()
    {
        int year;
        while (true)
        {
            year = Random.Shared.Next(1900, 2023);
            yield return year;
        }
    }
}

This method will keep on generating random years from 1900 to 2022 and return those. However, do not run this program yet as this is an infinite loop, and a foreach over it prints years until we kill the process.

So let’s add a break condition to stop the iteration once we encounter a leap year: 

public static IEnumerable<int> GenerateRandomYears()
{
    int year;
    while (true)
    {
        year = Random.Shared.Next(1900, 2023);
        yield return year;

        if (DateTime.IsLeapYear(year))
        {
            Console.WriteLine($"{Environment.NewLine}Encountered Leap Year:{year}");
            yield break;
        }
    }
}

Here we use a yield break statement to end the iterator block once we encounter a leap year.

Now, in Program.cs, let’s iterate through this iterator and print the years:

using YieldBreakInCSharp;

foreach (int year in Utility.GenerateRandomYears())
{
    Console.WriteLine(year);
}

Let’s run the application and observe the results:

1999
1991
1976

Encountered Leap Year:1976

As expected, this program produces a list of random years from 1900 to 2022 and ends the iteration once it encounters a leap year. We have seen how we can use a yield break statement to end an iteration.

How Is a yield break Different From a break Statement?

Now a lot of us might have this question in mind – Can we just use the break statement to end an iteration instead of the yield break statement? Well the answer is yes we can, but both these statements behave differently. We should be aware of the differences to use them in the correct context.

When execution reaches a break statement inside a loop, it terminates the loop and executes the next statement after the loop. It means that if we have other statements after the loop, the method still executes those before it exits.

On the other hand, when execution reaches a yield break statement inside an iterator block, it terminates the iterator block altogether and exits the method. It means that even if there are some additional statements after the loop, the method will not execute those. The compiler will even raise a warning that it has detected some unreachable code in this case.  We can think of the yield break statement inside an iterator method as something similar to a return statement inside a regular method that does not return anything.

An Example of yield break Statement Inside Iterator Method

For verifying this behavior, let’s add a second version of the method, GenerateRandomYearsWithUnreachableCode(), with a statement after the loop, and call it from the foreach in Program.cs:

public static IEnumerable<int> GenerateRandomYearsWithUnreachableCode()
{
    int year;
    while (true)
    {
        year = Random.Shared.Next(1900, 2023);
        yield return year;

        if (DateTime.IsLeapYear(year))
        {
            Console.WriteLine($"{Environment.NewLine}Encountered Leap Year:{year}");
            yield break;
        }
    }

    Console.WriteLine("GenerateRandomYears() method executed successfully.");
}

When we build, the compiler warns us that the last statement is unreachable:

warning CS0162: Unreachable code detected

Let’s run the application anyway and observe the output:

1987
1910
1993
2015
1913
1901
1996

Encountered Leap Year:1996

As expected, we can see that it does not execute the last statement. So a yield break statement exits the iterator without executing any further statements outside a finally block. 

An Example of break Statement Inside Iterator Method

Now let’s write a third version, GenerateRandomYearsWithBreak(), that uses a break statement instead of yield break, and call it from Program.cs:

public static IEnumerable<int> GenerateRandomYearsWithBreak()
{
    int year;
    while (true)
    {
        year = Random.Shared.Next(1900, 2023);
        yield return year;

        if (DateTime.IsLeapYear(year))
        {
            Console.WriteLine($"{Environment.NewLine}Encountered Leap Year:{year}");
            break;
        }
    }

    Console.WriteLine("GenerateRandomYears() method executed successfully.");
}

After that, let’s run the program once again to see the output:

2010
2010
2014
1967
2015
1987
1956

Encountered Leap Year:1956
GenerateRandomYears() method executed successfully.

This time we can see that it executes the print statement after the loop. 

Thus, even though we can use both break and yield break statements inside an iterator method, both behave differently and we should choose them carefully based on what we want to do.

How Is a yield break Different From a return Statement?

Another question that a lot of people may have in mind is: Can we just use the return statement to exit the iterator instead of using the yield break statement?

Well, a return statement terminates the execution of a regular method in which it appears and returns the control to the caller. While doing so, it can optionally return a value along with it. 

Now let’s try a version that uses a return statement instead. This code does not compile, which is the point of the example:

public static IEnumerable<int> GenerateRandomYearsWithReturn()
{
    int year;
    while (true)
    {
        year = Random.Shared.Next(1900, 2023);
        yield return year;

        if (DateTime.IsLeapYear(year))
        {
            Console.WriteLine($"{Environment.NewLine}Encountered Leap Year:{year}");
            return;
        }
    }
}

The build fails with this error:

error CS1622: Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration.

Notice that our return; doesn’t return a value at all. The compiler still reports CS1622: a return statement has no place in an iterator, with or without a value.

As the error shows, iterator methods are different from regular methods and do not support regular return statements. They can only use yield return and yield break statements. Before we move on, let’s delete GenerateRandomYearsWithReturn() so the project builds again.

This is a very important difference between iterator methods and regular methods. An iterator method can have “yield return” statements to return values one by one and yield break statements to exit the iterator. But we cannot use a regular return statement in an iterator method.

Does yield break Run the finally Block?

Yes. When an iterator reaches yield break inside a try block, the finally block runs before the iteration ends. A using declaration behaves the same way, because the compiler turns it into a try and finally pair, so the resource is disposed at yield break too.

That makes yield break safe in an iterator that holds a file or a database connection, because stopping early doesn’t leak it.

The same cleanup runs when the caller stops first. If the consumer breaks out of its foreach after two elements, the loop disposes the enumerator, and the iterator’s finally block runs at that moment.

yield break can’t sit inside a finally block, though: the compiler rejects it with error CS1625, “Cannot yield in the body of a finally clause”. Inside a try block or a catch block, it compiles fine.

Let’s add one more version of our method, GenerateRandomYearsWithCleanup(), that wraps the loop in a try block and writes a line from finally:

public static IEnumerable<int> GenerateRandomYearsWithCleanup()
{
    try
    {
        int year;
        while (true)
        {
            year = Random.Shared.Next(1900, 2023);
            yield return year;

            if (DateTime.IsLeapYear(year))
            {
                Console.WriteLine($"{Environment.NewLine}Encountered Leap Year:{year}");
                yield break;
            }
        }
    }
    finally
    {
        Console.WriteLine("The finally block ran.");
    }
}

When we call it from Program.cs, the last line of the output comes from the finally block:

1950
1928

Encountered Leap Year:1928
The finally block ran.

Conclusion

In this article, we learned the usage of yield break statements for iterators in C#. We learned how iterator methods are different from regular methods. Also, we learned how a yield break behaves differently from a break statement when we use it in iterator blocks. We also saw that the finally block still runs when an iterator reaches yield break.

Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0).