In C#, break, continue, and goto are statements used to control the flow inside loops and switch statements.
The break
statement immediately exits the nearest enclosing loop or switch
block.
for (int i = 1; i <= 10; i++)
{
if (i == 5)
break; // Exit loop when i is 5
Console.WriteLine(i);
}
Output:
1
2
3
4
The continue
statement skips the rest of the current loop iteration and proceeds to the next iteration.
for (int i = 1; i <= 5; i++)
{
if (i == 3)
continue; // Skip when i is 3
Console.WriteLine(i);
}
Output:
1
2
4
5
The goto
statement transfers control to a labeled statement within the same method. It can jump forward or backward, but its use is generally discouraged as it can make code harder to read.
int i = 1;
start: // Label
Console.WriteLine(i);
i++;
if (i <= 5)
goto start; // Jump back to 'start' label
Output:
1
2
3
4
5
When to Use?
break
: Exit a loop or switch early when a condition is met.continue
: Skip the current iteration but continue the loop.goto
: Rarely used; useful in complex scenarios like state machines or deeply nested loops, but use with caution.💡 Quick Tip:
Prefer break
and continue
for cleaner loops, and avoid goto
unless absolutely necessary.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!