C# Language Looping break

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Sometimes loop condition should be checked in the middle of the loop. The former is arguably more elegant than the latter:

for (;;)
{
    // precondition code that can change the value of should_end_loop expression

    if (should_end_loop)
        break;

    // do something
}

Alternative:

bool endLoop = false;
for (; !endLoop;)
{
    // precondition code that can set endLoop flag

    if (!endLoop)
    {
        // do something
    }
}

Note: In nested loops and/or switch must use more than just a simple break.



Got any C# Language Question?