C# Break & Continue
The break statement immediately exits a loop or switch statement, stopping further iterations. The continue statement skips the rest of the current iteration and moves to the next one.
Both are useful for controlling loop flow in more complex scenarios, such as stopping a search once a match is found, or skipping invalid data while processing a collection.
break;
continue;break
break immediately stops the loop entirely, and execution continues with the code right after the loop. It's often used once a desired result has been found.
continue
continue skips the remaining code in the current iteration and jumps to the next one, without exiting the loop entirely.
using System;
class Program {
static void Main() {
for (int i = 0; i < 10; i++) {
if (i == 3) {
break;
}
Console.WriteLine(i);
}
}
}0
1
2The loop stops entirely once i equals 3, thanks to break.
using System;
class Program {
static void Main() {
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue;
}
Console.WriteLine(i);
}
}
}0
1
3
4When i equals 2, continue skips printing and moves to the next iteration.
Key points
- break exits the loop entirely.
- continue skips only the current iteration.
- Both work inside for, while, and do-while loops.
- break also exits a switch statement's current case.
