C# Flow Control: A Practical Guide to Branching, Loops, and Jump Statements
By default, C# runs statements in the order they are written. This guide explains how branching, loops, and jump statements change that flow, covering syntax, execution rules, typical uses, and practical pitfalls.
Program code runs from top to bottom in the order it is written. That pattern is called sequential execution. It is simple, but it only handles a fixed path. It cannot choose different responses for different conditions, or repeat the same logic over a batch of data. Flow control exists to break that default order so a program can select a path or repeat a block of logic.
C# flow control falls into three groups: branching, loops, and jump statements. Used together, they form the skeleton of most business logic. This article covers their syntax, execution rules, typical scenarios, and recommended practices.
1. Branching: Choosing a Path by Condition
Branching is how a program makes a decision: run block A when a condition is true, and block B when it is not. C# provides the if family and the switch statement.
1.1 The if statement (single branch)
The simplest form runs a block only when the condition is true. Otherwise it skips the block:
if (condition){// Code that runs when the condition is true}
1.2 if-else (two branches)
if-else provides an alternative path when the condition is false:
if (condition){// Runs when the condition is true}else{// Runs when the condition is false}
1.3 if - else if - else (multiple branches)
Use this form when several mutually exclusive conditions must be tested in order. Evaluation proceeds from top to bottom. As soon as one condition is true, its block runs and the rest of the statement is skipped:
if (condition1){// Runs when condition1 is true}else if (condition2){// Runs when condition1 is false and condition2 is true}else{// Runs when every condition is false}
1.4 The switch statement (matching discrete values)
When the decision depends on several discrete values of one variable, switch is clearer than a long else if chain:
switch (day){case 1:Console.WriteLine("Monday");break;case 2:Console.WriteLine("Tuesday");break;case 6:case 7:Console.WriteLine("Weekend");break;default:Console.WriteLine("Invalid date");break;}
switch also supports richer pattern matching, such as when guards and type patterns, for more flexible branching. Each case must exit with break, goto case, return, or a similar jump. default handles every value that is not listed.
Branching guidelines
- Put the most likely, or the cheapest, condition first so evaluation finishes sooner.
- If an
else ifchain grows too long, preferswitchor a lookup structure such as a dictionary. - Keep conditions short. Extract complex logic into a named method or variable so the branch stays readable.
2. Loops: Repeating a Block
Loops run the same logic as many times as needed. They are the basis for processing collections, batches of data, and polling tasks.
2.1 The for loop (known iteration count)
Use for when the number of iterations is known, or when the loop variable follows a clear progression:
for (int i = 0; i < 10; i++){Console.WriteLine($"Iteration {i + 1}");}
The three parts are initialization (runs once), the condition (checked before each iteration; false exits the loop), and the iterator (runs after each pass through the body).
2.2 The while loop (test first)
Use while when the number of iterations is unknown and depends on a runtime condition:
int count = 0;while (count < 5){Console.WriteLine(count);count++;}
If the condition is false at the start, the body never runs. The body must change the condition; otherwise the loop never ends.
2.3 The do-while loop (run first, then test)
do-while guarantees that the body runs at least once. It fits cases where you must perform the work once before deciding whether to continue:
int input;do{Console.WriteLine("Enter a positive number:");input = int.Parse(Console.ReadLine());} while (input <= 0);
2.4 The foreach loop (iterating a collection)
foreach walks arrays and other types that implement IEnumerable. It manages the iterator for you, so you do not maintain an index and you avoid out-of-range errors:
string[] names = { "Alex", "Blake", "Casey" };foreach (string name in names){Console.WriteLine(name);}
Do not add or remove items in the collection while foreach is iterating it; that throws an exception. If you must change the collection, use a for loop or work on a copy.
3. Jump Statements: Changing the Flow
Jump statements change control flow from inside a branch or a loop.
3.1 break
break ends the innermost loop or switch immediately. Execution continues at the first statement after that structure. It is commonly used to leave early once a target is found:
for (int i = 0; i < 100; i++){if (data[i] == target){index = i;break; // Exit as soon as the target is found}}
3.2 continue
continue skips the rest of the current iteration and starts the next one. In a for loop the iterator still runs; in a while loop control returns to the condition:
for (int i = 0; i < 10; i++){if (i % 2 == 0){continue; // Skip even numbers}Console.WriteLine(i);}
3.3 return
return leaves the current method at once. No later code in that method runs, no matter how deeply it is nested. It is often used as a guard clause for early validation, which keeps nesting shallow:
public int Divide(int a, int b){if (b == 0){throw new ArgumentException("Divisor cannot be zero");}return a / b;}
3.4 goto
goto jumps unconditionally to a label in the same method. Modern C# rarely uses it, because it breaks structured flow and hurts readability. Use it only in rare cases, such as leaving several nested loops at once or falling through switch cases, and use it carefully.
3.5 throw
throw raises an exception and interrupts normal execution, handing the error to the caller. It belongs to exception-based flow control and, together with the jump statements above, completes the set of tools for governing program flow.
4. Combined Example: Branches and Loops Together
The following example grades a score band and processes several scores in a loop:
int[] scores = { 92, 75, 58, 86, 40 };foreach (int score in scores){if (score >= 90){Console.WriteLine($"{score}: Excellent");}else if (score >= 80){Console.WriteLine($"{score}: Good");}else if (score >= 60){Console.WriteLine($"{score}: Pass");}else{Console.WriteLine($"{score}: Fail");}}
5. Practices and Common Pitfalls
- Avoid deep nesting. Flatten nested
ifstatements with early returns or by combining conditions. More than about three levels is usually a sign to simplify. - Use Boolean expressions directly. Write
if (isValid)instead ofif (isValid == true). - Prevent infinite loops. In
whileanddo-while, the condition must be able to change. Infor, watch the iterator direction and the boundary. - Keep the loop body cheap. Do not repeat an expensive calculation or query that does not change inside the loop. Move it outside.
- Choose switch or a lookup. Prefer
switchfor value matching. For configurable matching, a dictionary of delegates is often clearer. Both are easier to maintain than a longelse ifchain. - break and continue affect only the nearest structure. To leave several nested loops at once, use a flag,
returnfrom a method, or—with care—agotolabel. - Do not modify a collection inside foreach. To add or remove items, use a reverse
forloop or operate on a copy.
6. Summary
C# flow control is built from branches, loops, and jump statements. Branches decide which path to take, loops decide how many times to take it, and jump statements decide when to leave early. Knowing their semantics, when to use each one, and how they work together is the step from code that runs to code that is easy to follow. In practice, favor readability and maintainability, and choose the form that matches the business meaning so the logic is obvious at a glance.
