Break vs Continue in C#: Key Differences and Usage
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#.
| Aspect | break | continue |
|---|---|---|
| Purpose | Exit the entire loop immediately | Skip current iteration, continue loop |
| Effect on loop | Stops loop completely | Loop continues with next iteration |
| Use case | Stop processing when condition met | Ignore certain iterations conditionally |
| Works in | for, while, do-while, switch | for, while, do-while |
| After execution | Control moves after loop | Control 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.
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); } } }
Continue Equivalent
This example shows how continue skips printing the number 3 but continues the loop.
using System; class Program { static void Main() { for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skip printing 3 } Console.WriteLine(i); } } }
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.break to stop processing when done or on error.continue to ignore specific cases but keep looping.break also works in switch.