C# Break and Continue
Sometimes you need to change the normal flow of a loop. The break keyword stops a loop early, and the continue keyword skips the rest of the current pass and jumps to the next one. These two small keywords give you fine control over exactly when your loop acts.
The break Keyword
break immediately ends the loop, even if the condition is still true. Execution jumps to the first line after the loop. It is useful when you have found what you were looking for and there is no reason to keep going.
Stop the loop at 3
for (int i = 0; i < 10; i++)
{
if (i == 3)
{
break;
}
Console.WriteLine(i);
}This prints 0, 1, and 2. When i reaches 3, break stops the loop before printing, so the numbers 3 through 9 never appear.
The continue Keyword
continue skips the remaining code in the current iteration and moves on to the next one. The loop itself keeps running; only the current pass is cut short.
Skip the number 3
for (int i = 0; i < 6; i++)
{
if (i == 3)
{
continue;
}
Console.WriteLine(i);
}This prints 0, 1, 2, 4, and 5. When i is 3, continue skips the WriteLine and jumps straight to the next value, so 3 is left out but the loop finishes normally.
break vs continue
Exercise: C# Break and Continue
In C#, when break is used inside a loop nested inside another loop, what does it do?