How C# Continue and Break Statements are Different?

Introduction

The continue and break statements in C# are control flow statements that are used to regulate the execution flow inside loops. They have different functions in regulating loop behavior. Let's examine these two statements' functions and uses.

Continue Statement in C#

To move on to the subsequent iteration of a loop and bypass the current iteration, use the continue statement. A loop that encounters a continue statement skips over the remaining code in the current iteration and moves straight on to the next one. This allows you to stop the loop without completely excluding iterations based on particular conditions.

Example of the continue statement in a for loop.

for (int i = 0; i < 5; i++) {

    if (i == 3) {
        continue; // Skips iteration when i equals 3.
    }

    Console.WriteLine(i);
}

In this example, the continue statement skips the iteration when i equals 3, resulting in an output of 0, 1, 2, and 4.

Break Statement in C#

On the other hand, a loop can be prematurely ended by using the break statement. A loop is instantly broken when a break statement is found, and control is moved to the statement that comes after the loop. This lets you, under certain circumstances, get out of the loop early.

An illustration of a for loop's break statement is this.

for (int i = 0; i < 5; i++) {

    if (i == 3) {
        break; // Exits the loop when i equals 3.
    }

    Console.WriteLine(i);
}

In this case, the loop is broken by the break statement when i equals 3, producing the values 0 through 2.

The Bottom Line

The continue and break statements in C# are valuable tools for controlling the behavior of loops. The continue statement allows you to skip the current iteration and proceed to the next iteration, while the break statement enables you to exit the loop prematurely. By using these statements effectively, you can tailor the execution of your loops to meet specific requirements and conditions, enhancing the flexibility and control of your C# programs.


Similar Articles