continue vs break in C#

HomeC#

continue vs break in C#

Exploring LINQ to Objects: Powerful Data Manipulation in C#
Get contents of HTML style tag in ASP.NET using C#
Implicit Index Access in C#

continue and break are like little control switches you can use inside loops in C#. They give you the power to alter the normal flow of iteration. Let me show you what I mean:

break Statement:

Imagine you’re searching through a list of items. Once you find what you’re looking for, there’s no need to keep searching, right? That’s exactly what break does. It immediately terminates the entire loop (either for, while, do-while, or foreach) and transfers control to the statement immediately following the loop.

Here’s an example:

for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        Console.WriteLine("Found the number 5! Exiting the loop.");
        break; // Exit the loop immediately
    }
    Console.WriteLine($"Checking number: {i}");
}

Console.WriteLine("Loop finished.");

In this code, as soon as i becomes 5, the break statement is executed. The loop stops right there, and the output will be:

Checking number: 0
Checking number: 1
Checking number: 2
Checking number: 3
Checking number: 4
Found the number 5! Exiting the loop.
Loop finished.

Notice that the numbers 6, 7, 8, and 9 are never checked.

continue Statement:

Now, let’s say you’re processing a list, and you encounter an item you want to skip but still want to process the rest of the list. That’s where continue comes in handy. It stops the current iteration of the loop and jumps to the beginning of the next iteration.

Here’s an example:

for (int i = 0; i < 10; i++)
{
    if (i % 2 == 0) // If the number is even
    {
        Console.WriteLine($"Skipping even number: {i}");
        continue; // Skip to the next iteration
    }
    Console.WriteLine($"Processing odd number: {i}");
}

Console.WriteLine("Loop finished.");

In this example, when i is even, the continue statement is executed. The rest of the code inside the loop for that particular iteration is skipped, and the loop moves on to the next value of i. The output will be:

Skipping even number: 0
Processing odd number: 1
Skipping even number: 2
Processing odd number: 3
Skipping even number: 4
Processing odd number: 5
Skipping even number: 6
Processing odd number: 7
Skipping even number: 8
Processing odd number: 9
Loop finished.

So, in a nutshell:

  • break: Gets you out of the entire loop immediately.
  • continue: Skips the current iteration and moves to the next one.

They are both powerful tools for controlling the flow of your loops and making your code more efficient and tailored to specific conditions.

Older Post

COMMENTS

DISQUS: 0