break

suggest change

In a loop (for, foreach, do, while) the break statement aborts the execution of the innermost loop and returns to the code after it. Also it can be used with yield in which it specifies that an iterator has come to an end.

for (var i = 0; i < 10; i++)
{
    if (i == 5)
    {
        break;
    }
    Console.WriteLine("This will appear only 5 times, as the break will stop the loop.");
}

Live Demo on .NET Fiddle

foreach (var stuff in stuffCollection)
{
    if (stuff.SomeStringProp == null)
        break;
    // If stuff.SomeStringProp for any "stuff" is null, the loop is aborted.
    Console.WriteLine(stuff.SomeStringProp);
}

The break-statement is also used in switch-case constructs to break out of a case or default segment.

switch(a)
{
    case 5:
        Console.WriteLine("a was 5!");
        break;

    default:
        Console.WriteLine("a was something else!");
        break;
}

In switch statements, the ‘break’ keyword is required at the end of each case statement. This is contrary to some languages that allow for ‘falling through’ to the next case statement in the series. Workarounds for this would include ‘goto’ statements or stacking the ‘case’ statements sequentially.

Following code will give numbers 0, 1, 2, ..., 9 and the last line will not be executed. yield break signifies the end of the function (not just a loop).

public static IEnumerable<int> GetNumbers()
{
    int i = 0;
    while (true) {
        if (i < 10) {
            yield return i++;
        } else {
            yield break;
        }
    }
    Console.WriteLine("This line will not be executed");
}

Live Demo on .NET Fiddle

Note that unlike some other languages, there is no way to label a particular break in C#. This means that in the case of nested loops, only the innermost loop will be stopped:

foreach (var outerItem in outerList)
{
    foreach (var innerItem in innerList)
    {
        if (innerItem.ShoudBreakForWhateverReason)
            // This will only break out of the inner loop, the outer will continue:
            break; 
    }
}

If you want to break out of the outer loop here, you can use one of several different strategies, such as:

bool shouldBreak = false;
while(comeCondition)
{
    while(otherCondition)
    {
        if (conditionToBreak)
        {
            // Either tranfer control flow to the label below...
            goto endAllLooping;

            // OR use a flag, which can be checked in the outer loop:
            shouldBreak = true;
        }
    }

    if(shouldBreakNow)
    {
        break; // Break out of outer loop if flag was set to true
    }
}

endAllLooping: // label from where control flow will continue

Feedback about page:

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



Table Of Contents