C# control flow and operators
This page covers two related problems: leaving or skipping work at the right point (loops, nested loops and guard clauses), and making arithmetic and operators behave exactly as intended (overflow detection, bit shifts, and in-place updates on your own types). It starts with the oldest statements in the language and ends with the newest operator feature, so it also works as a reading path.
Every sample uses the invented OrdersPortal order-management app. Unless a section says otherwise, each sample is a complete file-based app: save it as sample.cs and run dotnet run sample.cs with the .NET 10 SDK (C# 14). The outputs shown were produced with .NET SDK 10.0.115. The labeled break and continue sample needs the .NET 11 SDK (C# 15) and is marked “not compiled here”.
Features on this page
Section titled “Features on this page”| Feature | Version | Use it when |
|---|---|---|
| Break and continue | C# 1 | Stop a loop early, or skip one iteration. |
| Labeled break and continue | C# 15 | Leave or continue an outer loop from inside a nested one. |
| Throw expressions | C# 7.0 | A guard or fallback belongs inside an expression. |
| Checked and unchecked arithmetic | C# 1, user-defined checked operators C# 11 | Integer overflow must be detected, or wraparound is intended. |
| Unsigned right shift | C# 11 | Shifting a signed value without copying the sign bit. |
| User-defined compound assignment | C# 14 | += on your mutable type should update in place instead of allocating. |
Break and continue
Section titled “Break and continue”Introduced in C# 1 (.NET Framework 1.0). break ends the innermost enclosing for, foreach, while, do or switch statement immediately. continue ends only the current iteration of the innermost loop and moves to the next one (re-evaluating the condition, or running the for iterator first). Use continue for “this item does not apply” filters at the top of a loop body, and break for “nothing after this is useful”, such as finding the first match or hitting corrupt data. Inside a switch that sits in a loop, break exits the switch, not the loop, which is a frequent source of confusion.
decimal[] lineTotals = [12.50m, 0m, 30m, -1m, 99m];decimal invoiceTotal = 0;
foreach (var amount in lineTotals){ if (amount == 0m) continue; // skip free lines, keep looping if (amount < 0m) { Console.WriteLine("Negative line found, stopping"); break; // corrupt data: stop the whole loop } invoiceTotal += amount;}Console.WriteLine($"Invoiced: {invoiceTotal}");
for (int attempt = 1; attempt <= 3; attempt++){ switch (attempt) { case 2: Console.WriteLine("break inside switch leaves only the switch"); break; default: Console.WriteLine($"attempt {attempt}"); break; }}Output:
Negative line found, stoppingInvoiced: 42.50attempt 1break inside switch leaves only the switchattempt 3Pitfalls:
breakin aswitchinside a loop does not stop the loop. Use a labeledbreak(C# 15), areturn, or a flag.- In a
whileloop,continueskips any increment written at the bottom of the body, which can create an infinite loop. continuecannot target aswitch; it always applies to a loop.
Labeled break and continue
Section titled “Labeled break and continue”Introduced in C# 15 (.NET 11, November 2026); not a preview feature. A break or continue can now name a label placed directly on an enclosing loop (or, for break, an enclosing switch): break outer; leaves that statement, and continue outer; starts its next iteration. Before C# 15, escaping nested loops needed a Boolean flag tested at every level, a goto to a label after the loops, or moving the loops into a method so you could return. The new form states the intended target on the jump itself. The IDE0410 style rule suggests this rewrite for flag and goto patterns. Without a label, both statements keep their original meaning.
Not compiled here (needs .NET 11 SDK); syntax verified against the Microsoft Learn C# 15 documentation.
string[][] racks =[ ["SKU-1", "SKU-2", "LOCKED", "SKU-9"], ["SKU-3", "SKU-9", "SKU-4"], ["SKU-9"],];string wanted = "SKU-9";
search: for (int rack = 0; rack < racks.Length; rack++){ for (int bin = 0; bin < racks[rack].Length; bin++) { if (racks[rack][bin] == "LOCKED") { Console.WriteLine($"rack {rack} is locked, skipping"); continue search; // next rack, not next bin } if (racks[rack][bin] == wanted) { Console.WriteLine($"{wanted} found in rack {rack}, bin {bin}"); break search; // stop searching every rack } }}Expected output:
rack 0 is locked, skippingSKU-9 found in rack 1, bin 1Pitfalls:
- The label must sit directly on the loop or
switchit names; labeling a block that contains the loop does not work. continuewith a label still has to name a loop, never aswitch.- Three or more nested loops with labeled jumps are still hard to follow. Extracting a method that returns the result is often clearer.
Throw expressions
Section titled “Throw expressions”Introduced in C# 7.0. throw can be used as an expression in three places: the right operand of ??, either branch of the conditional operator ?:, and the body of an expression-bodied member or lambda. Switch expression arms (C# 8) accept it too. That lets a guard live inside the assignment or expression it protects, for example Email = email ?? throw new ArgumentNullException(nameof(email)) in a constructor, or a final _ => throw arm for an unknown value. A throw expression has no type of its own; it takes whatever type the context needs.
var customer = new Customer("Wide World Importers", "billing@example.test");Console.WriteLine(customer.Email);
try{ _ = new Customer("Lucerne Publishing", null);}catch (ArgumentNullException ex){ Console.WriteLine($"Missing: {ex.ParamName}");}
Console.WriteLine(Discount("GOLD"));try { Discount("PLATINUM"); }catch (ArgumentException ex) { Console.WriteLine(ex.Message); }
static decimal Discount(string tier) => tier switch{ "STANDARD" => 0m, "GOLD" => 0.1m, _ => throw new ArgumentException($"Unknown tier '{tier}'", nameof(tier)),};
public sealed class Customer(string name, string? email){ public string Name { get; } = name; public string Email { get; } = email ?? throw new ArgumentNullException(nameof(email));}Output:
billing@example.testMissing: email0.1Unknown tier 'PLATINUM' (Parameter 'tier')Pitfalls:
throwis not allowed as a standalone expression elsewhere, for example as anifcondition or a method argument.- For plain parameter checks,
ArgumentNullException.ThrowIfNull(x)(.NET 6) andArgumentException.ThrowIfNullOrEmpty(x)(.NET 7) are shorter and produce the parameter name automatically.
Checked and unchecked arithmetic
Section titled “Checked and unchecked arithmetic”Introduced in C# 1 (.NET Framework 1.0); user-defined checked operators were added in C# 11 (.NET 7). Integer arithmetic in C# wraps around on overflow by default: int.MaxValue + 1 becomes int.MinValue with no error. A checked(...) expression or checked { } block makes overflowing integral arithmetic and narrowing conversions throw OverflowException; unchecked explicitly asks for wraparound. The project-wide default comes from the CheckForOverflowUnderflow compiler option. Since C# 11, a type can declare operator checked + next to its regular operator +, and the compiler picks the checked one inside a checked context.
int stockUnits = int.MaxValue - 1;
int wrapped = unchecked(stockUnits + 5); // silent wraparound (the default context)Console.WriteLine(wrapped);
try{ int safe = checked(stockUnits + 5); // overflow is a bug here: fail loudly Console.WriteLine(safe);}catch (OverflowException ex){ Console.WriteLine($"checked: {ex.Message}");}
var a = new Quantity(int.MaxValue);Console.WriteLine((a + new Quantity(1)).Value); // calls operator +try{ Console.WriteLine(checked(a + new Quantity(1)).Value); // calls operator checked +}catch (OverflowException){ Console.WriteLine("Quantity overflow detected");}
public readonly record struct Quantity(int Value){ public static Quantity operator +(Quantity l, Quantity r) => new(unchecked(l.Value + r.Value)); public static Quantity operator checked +(Quantity l, Quantity r) => new(checked(l.Value + r.Value));}Output:
-2147483645checked: Arithmetic operation resulted in an overflow.-2147483648Quantity overflow detectedPitfalls:
checkedaffects only the expressions written inside it, not methods called from there. A method called insidechecked(...)uses its own context.decimalalways throws on overflow andfloat/doublenever do (they produce infinity), whatever the context.- A
checkedoperator requires a matching regular operator (error CS9025).
Unsigned right shift
Section titled “Unsigned right shift”Introduced in C# 11 (.NET 7). The >>> operator shifts bits right and always fills the vacated high bits with zeros. The ordinary >> on a signed type is an arithmetic shift: it copies the sign bit, so a negative number stays negative. Before C# 11 you had to cast to the unsigned type, shift, and cast back, (int)((uint)value >> 2), which is noisy and awkward in generic math code. >>> and >>>= are defined for all integral types and can be overloaded, and IShiftOperators exposes them for generic math.
int packed = -8; // 0xFFFFFFF8
Console.WriteLine($"{packed >> 1,11} {packed >> 1:X8}"); // arithmetic: sign bit copied inConsole.WriteLine($"{packed >>> 1,11} {packed >>> 1:X8}"); // logical: zeros shifted in
// Pick one of 16 shards from the top 4 bits of an order hash.int orderHash = unchecked((int)0xB3A1_0F42); // a hash that happens to be negativeConsole.WriteLine($"shard with >> : {orderHash >> 28}"); // negative: unusable as an indexConsole.WriteLine($"shard with >>> : {orderHash >>> 28}"); // 0..15Output:
-4 FFFFFFFC 2147483644 7FFFFFFCshard with >> : -5shard with >>> : 11Pitfalls:
>>>on a negative number is not division by a power of two; use>>(or/) for arithmetic.- The shift count is masked to the operand size (low 5 bits for
int), sox >>> 32returnsxunchanged.
User-defined compound assignment
Section titled “User-defined compound assignment”Introduced in C# 14 (.NET 10). A class or struct can now declare compound assignment operators directly: public void operator +=(decimal value). The operator is an instance method with one parameter and a void return type, and it updates the receiver in place. Before C# 14, x += y on a user-defined type always meant x = x + y, which calls the static binary + and allocates or copies a new value; for large mutable types such as buffers, matrices or accumulators that cost was real. All compound operators can be declared this way, checked versions of +=, -=, *= and /= included, and instance ++ and -- operators were added at the same time. If a type does not declare one, the compiler falls back to the binary operator as before.
var totals = new RunningTotal();totals += 19.99m; // calls the instance operator +=, no new objecttotals += 5.01m;totals -= 2.00m;Console.WriteLine(totals);
var before = totals;before += 100m;Console.WriteLine(ReferenceEquals(before, totals)); // same instance was mutatedConsole.WriteLine(totals);
public sealed class RunningTotal{ public decimal Amount { get; private set; } public int Updates { get; private set; }
public void operator +=(decimal value) { Amount += value; Updates++; } public void operator -=(decimal value) { Amount -= value; Updates++; }
// The binary operator still exists for x + y; it must return a new instance. public static RunningTotal operator +(RunningTotal left, decimal value) => new() { Amount = left.Amount + value, Updates = left.Updates + 1 };
public override string ToString() => $"{Amount} after {Updates} updates";}Output:
23.00 after 3 updatesTrue123.00 after 4 updatesPitfalls:
- In-place mutation is visible through every reference. Above,
before += 100malso changedtotals, which would not happen with the binary-operator fallback. - Keep
+=and+consistent: callers expectx += yandx = x + yto produce the same value. - Do not add compound operators to immutable value objects; the binary operator already gives the right semantics.
Choosing between them
Section titled “Choosing between them”- Nested loop exit: on C# 15, a labeled
break; on earlier versions, extract a method andreturn, and only then fall back to a flag. - Guard clause:
ThrowIfNull-style helpers for parameters, a throw expression for fallbacks inside an expression, a plainifwiththrowfor anything longer. - Money, quantities, counters that must never wrap:
checked(ordecimal). Hashes and checksums that are meant to wrap:uncheckedwritten explicitly. - In-place update operator: only on mutable types where avoiding the allocation is measured to matter.
Interview questions
Section titled “Interview questions”What does break do inside a switch that is inside a for loop?
It exits the switch only; the loop continues with its next iteration. To leave the loop you need return, a flag, a goto, or in C# 15 a labeled break that names the loop.
Why might checked code not throw when a called method overflows?
The checked context is lexical. It applies to arithmetic written inside the checked expression or block, not to code in other methods. Use the CheckForOverflowUnderflow project setting to change the default for a whole assembly.
What is the difference between >> and >>> on an int?
>> is an arithmetic shift that replicates the sign bit, so negative numbers stay negative. >>> is a logical shift that fills with zeros, so the result is non-negative for any shift count above zero.
Before C# 14, what did x += y compile to for a user-defined type, and what changed?
It compiled to x = x + y using the static binary operator, which creates a new value. C# 14 lets the type declare an instance operator += that mutates x in place; the compiler prefers it when present.
Senior scenario: an OrdersPortal loyalty-points service stores balances as int. A promotion multiplied points and some customers ended up with negative balances. What do you change?
The multiplication overflowed silently because C# defaults to unchecked arithmetic. Short term, wrap balance arithmetic in checked (or enable CheckForOverflowUnderflow for the domain project) so overflow throws instead of corrupting data, and add validation on the multiplier. Longer term, widen to long or decimal, wrap the balance in a value type whose operators are checked, and add tests at int.MaxValue boundaries.
Related pages
Section titled “Related pages”- Methods, lambdas and extensions: extension operators and the local functions often used instead of nested loops.
- Types, records and unions: the switch expressions and discards used in guard clauses.
- Pattern matching: switch expressions, the main home of
_ => throwarms. - Null handling:
??and null-conditional operators that pair with throw expressions. - C# 14 release guide, C# 15 release guide and C# version history.
Official references
Section titled “Official references”- Jump statements: break, continue, return, goto (including labeled jumps)
- IDE0410: Use labeled break or continue
- throw expressions
- checked and unchecked statements
- Arithmetic operators: user-defined checked operators and compound assignment
- Bitwise and shift operators
- User-defined compound assignment feature specification (C# 14)
- What’s new in C# 15