Summary#
break leaves the enclosing loop. continue abandons this pass and goes to the next one. Both behave exactly as in
C# — including the part that catches people out: inside a switch, break leaves the switch, not the loop around
it.
Signature#
break; // stop looping
continue; // skip the rest of this passDescription#
continue — skip this one#
entity Order {
[Required] string Code;
decimal Total;
bool Cancelled;
}
decimal LiveTotal() {
var total = 0m;
foreach (var o in Order.Where(x => x.Total > 0).ToList()) {
if (o.Cancelled) { continue; } // not this one — next
total += o.Total;
}
return total;
}break — stop entirely#
string FirstBig(decimal threshold) {
var found = "";
foreach (var o in Order.Where(x => x.Total > 0).ToList()) {
if (o.Total >= threshold) {
found = o.Code;
break; // done — no point looking further
}
}
return found;
}Why didn't break leave my loop? — the switch trap#
This is the one to remember. Inside a switch that sits in a loop, break ends the switch, and execution
continues after it — inside the same pass of the loop. It does not leave the loop.
continue, by contrast, passes straight through the switch and continues the loop:
int SumNonZero(int[] xs) {
var total = 0;
for (int i = 0; i < xs.Length; i++) {
switch (xs[i]) {
case 0: continue; // skips to the next i — the loop's next pass
default: break; // leaves the SWITCH; falls through to the += below
}
total += xs[i];
}
return total;
}If you want to leave the loop from inside a switch, you need a flag, or to restructure the loop — exactly as in C#. This is not a wart we introduced; it is C#'s rule, and we kept it rather than invent a different one you would have to learn twice.