How to Use Continue in C#: Syntax and Examples
In C#, the
continue statement skips the rest of the current loop iteration and moves to the next iteration immediately. It works inside loops like for, while, and foreach to control flow by ignoring certain steps conditionally.Syntax
The continue statement is used inside loops to skip the remaining code in the current iteration and jump to the next iteration.
It can be used in for, while, and foreach loops.
Basic syntax:
continue;- skips to the next loop iteration immediately.
csharp
for (int i = 0; i < 5; i++) { if (i == 2) { continue; // Skip when i is 2 } Console.WriteLine(i); }
Output
0
1
3
4
Example
This example shows how continue skips printing the number 3 in a loop from 1 to 5.
csharp
using System; class Program { static void Main() { for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skip printing 3 } Console.WriteLine(i); } } }
Output
1
2
4
5
Common Pitfalls
Common mistakes when using continue include:
- Using
continueoutside of loops causes a compile error. - Forgetting that
continueskips only the current iteration, not the entire loop. - Placing
continuewhere it causes infinite loops, especially inwhileloops without updating the loop variable.
Example of a wrong and right usage:
csharp
int i = 0; while (i < 5) { i++; if (i == 3) { continue; // Correct: increments i before continue } Console.WriteLine(i); } // Wrong usage (infinite loop): // int j = 0; // while (j < 5) // { // if (j == 3) // { // continue; // j never increments, loop stuck // } // j++; // Console.WriteLine(j); // }
Output
1
2
4
5
Quick Reference
Summary tips for using continue in C# loops:
| Tip | Description |
|---|---|
| Use inside loops only | Works only in for, while, and foreach loops. |
| Skips current iteration | Jumps to the next iteration immediately. |
| Avoid infinite loops | Ensure loop variables update before continue. |
| Use for conditional skipping | Commonly used with if statements to skip certain cases. |
Key Takeaways
The continue statement skips the rest of the current loop iteration and moves to the next one.
Use continue only inside loops like for, while, and foreach.
Always update loop variables before continue to avoid infinite loops.
Continue is useful to conditionally skip specific steps in a loop.
Using continue outside loops causes a compile-time error.