The difference between break and yield break

suggest change

Using yield break as opposed to break might not be as obvious as one may think. There are lot of bad examples on the Internet where the usage of the two is interchangeable and doesn’t really demonstrate the difference.

The confusing part is that both of the keywords (or key phrases) make sense only within loops (foreach, while…) So when to choose one over the other?

It’s important to realize that once you use the yield keyword in a method you effectively turn the method into an iterator. The only purpose of the such method is then to iterate over a finite or infinite collection and yield (output) its elements. Once the purpose is fulfilled, there’s no reason to continue method’s execution. Sometimes, it happens naturally with the last closing bracket of the method \}. But sometimes, you want to end the method prematurely. In a normal (non-iterating) method you would use the return keyword. But you can’t use return in an iterator, you have to use yield break. In other words, yield break for an iterator is the same as return for a standard method. Whereas, the break statement just terminates the closest loop.

Let’s see some examples:

/// Yields numbers from 0 to 9
/// </summary>
/// <returns>{0,1,2,3,4,5,6,7,8,9}</returns>
public static IEnumerable<int> YieldBreak()
{
    for (int i = 0; ; i++)
    {
        if (i < 10)
        {
            // Yields a number
            yield return i;
        }
        else
        {
            // Indicates that the iteration has ended, everything 
            // from this line on will be ignored
            yield break;
        }
    }
    yield return 10; // This will never get executed
}

/// <summary>
/// Yields numbers from 0 to 10
/// </summary>
/// <returns>{0,1,2,3,4,5,6,7,8,9,10}</returns>
public static IEnumerable<int> Break()
{
    for (int i = 0; ; i++)
    {
        if (i < 10)
        {
            // Yields a number
            yield return i;
        }
        else
        {
            // Terminates just the loop
            break;
        }
    }
    // Execution continues
    yield return 10;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents