0
0
CsharpComparisonBeginner · 3 min read

Break vs Continue in C#: Key Differences and Usage

In C#, break immediately exits the entire loop, stopping all further iterations. In contrast, continue skips the current iteration and moves to the next one without exiting the loop.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of break and continue in C#.

Aspectbreakcontinue
PurposeExit the entire loop immediatelySkip current iteration, continue loop
Effect on loopStops loop completelyLoop continues with next iteration
Use caseStop processing when condition metIgnore certain iterations conditionally
Works infor, while, do-while, switchfor, while, do-while
After executionControl moves after loopControl moves to next iteration
⚖️

Key Differences

The break statement in C# is used to exit a loop or a switch statement immediately. When break runs, the program stops the current loop and continues execution from the code after the loop. This is useful when you want to stop looping as soon as a certain condition is met.

On the other hand, continue does not exit the loop but skips the rest of the current iteration. It immediately jumps to the next iteration of the loop. This is helpful when you want to ignore some iterations based on a condition but still want the loop to keep running.

In summary, break stops the loop completely, while continue only skips one loop cycle and continues looping.

⚖️

Code Comparison

Below is an example showing how break works to stop a loop when a number equals 3.

csharp
using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 5; i++)
        {
            if (i == 3)
            {
                break; // Exit loop when i is 3
            }
            Console.WriteLine(i);
        }
    }
}
Output
1 2
↔️

Continue Equivalent

This example shows how continue skips printing the number 3 but continues the loop.

csharp
using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 5; i++)
        {
            if (i == 3)
            {
                continue; // Skip printing 3
            }
            Console.WriteLine(i);
        }
    }
}
Output
1 2 4 5
🎯

When to Use Which

Choose break when you want to stop looping entirely as soon as a condition is met, like finding a match or an error. Use continue when you want to skip certain loop steps but keep processing the rest, such as ignoring invalid data but continuing with others.

In short, use break to exit loops early, and continue to skip specific iterations without stopping the loop.

Key Takeaways

break exits the entire loop immediately.
continue skips the current iteration and continues looping.
Use break to stop processing when done or on error.
Use continue to ignore specific cases but keep looping.
Both work inside loops; break also works in switch.