C#•Loop Control
C# Break and Continue Statements in Loops
break terminates loop execution immediately; continue skips to the next iteration.
Syntax
if (condition) break;
if (condition) continue;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| break | Keyword | Exits loop completely. |
| continue | Keyword | Skips remainder of current iteration. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C# locally:
using System;
public class Program {
public static void Main() {
int[] portCodes = {80, 443, -1, 8080, 9999, 3000};
Console.WriteLine("Scanning ports:");
foreach (int port in portCodes) {
if (port < 0) {
Console.WriteLine($" [SKIP] Invalid port: {port}");
continue;
}
if (port == 9999) {
Console.WriteLine(" [STOP] Sentinel port 9999 hit. Halting scan.");
break;
}
Console.WriteLine($" [OPEN] Active port: {port}");
}
}
}Expected Output:
Scanning ports: [OPEN] Active port: 80 [OPEN] Active port: 443 [SKIP] Invalid port: -1 [OPEN] Active port: 8080 [STOP] Sentinel port 9999 hit. Halting scan.
How It Works: Step-by-Step
- Lines 9-12: continue skips -1.
- Lines 13-16: break halts scan upon 9999.
Key Concepts
- continue skips to the next item in foreach/for.
- break terminates only the innermost loop.
Common Mistake: Using continue before incrementing in while loop
Skipping the increment in while loops causes an infinite loop.
❌ Incorrect
while (i < 5) { if (i == 2) continue; i++; }✅ Correct
while (i < 5) { if (i == 2) { i++; continue; } i++; }Related C# Tutorials & Compiler
C# Generic List Collections Iteration Mechanics via Foreach
Master generic List<T> collection traversal in C# using foreach, understanding IEnumerable<T> enumerator state and read-only cursor safety.
C# While and Do-While Loops with Examples
Master pre-test while loops and post-test do-while loops in C#.
C# Pattern Matching Switch Statements and Expressions
Implement modern C# pattern matching switch expressions (=>) with relational ranges, logical combinators (and/or), and discard guards.
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.