C# break Statement

In C#, the break statement is used to immediately exit a loop, such as a for, while, or do...while loop. When the break statement is encountered, the program exits the loop and continues executing the code that follows the loop.

Here is an example that uses the break statement in a for loop:

refe‮:ot r‬theitroad.com
for (int i = 1; i <= 10; i++)
{
    if (i == 5)
    {
        break;
    }
    Console.WriteLine(i);
}

In this example, the for loop iterates over the values of i from 1 to 10. However, when i is equal to 5, the break statement is executed, which immediately exits the loop. As a result, only the values of i from 1 to 4 are printed to the console.

Note that the break statement can also be used in a switch statement to exit the switch block. In addition, the break statement can be used inside nested loops to exit the innermost loop.