C# Break vs Continue: Key Differences Explained
In C#, break and continue are two control flow statements used to alter the flow of execution in a loop.
- The break statement is used to immediately stop the execution of a loop and exit the loop body. When the break statement is executed, the loop will stop immediately, and the program flow will exit the loop body. It is typically used when a certain condition is met inside the loop body to prematurely terminate the loop.
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
- The continue statement is used to skip the remaining code in the current loop and proceed directly to the next iteration of the loop. When the continue statement is executed, the remaining code in the current iteration is skipped and the next iteration is immediately executed. The continue statement is typically used in a loop when a certain condition is not met, allowing the current iteration to be skipped.
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
continue;
}
Console.WriteLine(i);
}
Therefore, ‘break’ is used to terminate a loop prematurely, while ‘continue’ is used to skip the current iteration. This is the main difference between ‘break’ and ‘continue’.