C# control flow, methods and exceptions
This is the second page of the C# basics path. The first page showed how to store and combine values; this one shows how a program makes decisions, repeats work, packages logic into reusable methods and reacts when something goes wrong. The samples continue the invented OrdersPortal shop: they route orders by status, price order lines and reject bad input.
What you’ll build
Section titled “What you’ll build”You will finish with a small checkout program that reads order lines as text ("CABLE-01;3"), validates each line, prices the valid ones with a bulk discount, picks a shipping class and reports the lines it rejected without crashing. To get there you will use if, switch statements and switch expressions, the four loop statements, methods with several kinds of parameters, and try, catch and finally.
Prerequisites
Section titled “Prerequisites”- The .NET 10 SDK or later. The samples were compiled and run with .NET SDK 10.0.115 (C# 14). The newest syntax used is the relational pattern
<= 5in aswitchexpression, which needs C# 9. - The console project from the previous page, or a new one made with
dotnet new console -o OrdersPortal.Basics. ReplaceProgram.cswith each sample and rundotnet run. - Comfort with variables, operators and arrays, from types, variables and operators.
Control flow
Section titled “Control flow”Control flow statements decide which code runs and how often. C# has three families:
- Selection:
if,else ifandelsetest conditions in order and run the first branch whose condition istrue. Aswitchstatement compares one value against severalcaselabels. - Iteration:
forrepeats with a counter,foreachvisits every element of an array or collection,whilerepeats while a condition holds (possibly zero times), anddo…whilealways runs its body at least once. - Jumps:
breakleaves the nearest loop orswitch,continueskips to the next loop iteration, andreturnleaves the method.
A switch expression (C# 8 and later) is the value-producing cousin of the switch statement: each arm is pattern => value, and _ matches anything left over. It reads well whenever every branch only chooses a value.
string[] statuses = { "Pending", "Paid", "Shipped", "Cancelled", "Unknown" };int[] itemCounts = { 1, 3, 12, 0, 2 };
for (int i = 0; i < statuses.Length; i++){ string status = statuses[i]; int items = itemCounts[i];
// if / else if / else: test conditions in order, run the first match if (items == 0) { Console.WriteLine($"Order {i + 1}: empty, skipped"); continue; // jump to the next loop iteration } else if (items > 10) { Console.WriteLine($"Order {i + 1}: bulk order, needs a pallet"); }
// switch statement: run a block per case; every section must end with break, return, throw or continue switch (status) { case "Pending": Console.WriteLine($"Order {i + 1}: waiting for payment"); break; case "Paid": case "Shipped": // stacked labels share one block Console.WriteLine($"Order {i + 1}: in fulfilment ({status})"); break; default: Console.WriteLine($"Order {i + 1}: unexpected status '{status}'"); break; }
// switch expression (C# 8): pick a value; _ is the catch-all arm string speed = items switch { 1 => "letter post", <= 5 => "small parcel", // relational pattern (C# 9) _ => "freight", }; Console.WriteLine($" shipping: {speed}");}
// while: repeat while a condition is true (may run zero times)int stock = 5;while (stock > 0){ stock -= 2;}Console.WriteLine($"Stock after picking: {stock}");
// do-while: runs the body at least onceint attempts = 0;do{ attempts++;} while (attempts < 3);Console.WriteLine($"Attempts: {attempts}");
// foreach with break: stop at the first matchforeach (string s in statuses){ if (s == "Shipped") { Console.WriteLine("Found the first shipped order"); break; }}Output:
Order 1: waiting for payment shipping: letter postOrder 2: in fulfilment (Paid) shipping: small parcelOrder 3: bulk order, needs a palletOrder 3: in fulfilment (Shipped) shipping: freightOrder 4: empty, skippedOrder 5: unexpected status 'Unknown' shipping: small parcelStock after picking: -1Attempts: 3Found the first shipped orderTwo rules surprise people coming from C, C++ or JavaScript. First, a switch section cannot fall through into the next one: every non-empty section must end with break, return, throw, continue or goto case, otherwise the compiler reports CS0163. Stacking labels with no code between them, as "Paid" and "Shipped" do, is allowed. Second, conditions must be bool; if (items) with an int does not compile.
The while loop shows why you should think about the exit condition: stock ends at -1 because the loop subtracts 2 from an odd number. Nothing stops a loop from overshooting except your condition. When an exit depends on several things, prefer a clear condition over a while (true) with scattered break statements. The control flow and operators hub covers break and continue in depth, labeled break and continue (C# 15) and throw expressions, and the pattern matching hub covers every pattern you can use in switch.
Methods
Section titled “Methods”A method is a named block of code with a return type (void when it returns nothing), a name and a parameter list. Methods live inside a type; here they are static methods of a static class OrderMath, which means you call them through the class name without creating an object. The classes and objects page explains static in detail.
C# gives you several ways to shape parameters:
- Default values:
int quantity = 1makes the argument optional. - Named arguments:
LineTotal(unitPrice: 5m, quantity: 4)documents the call and lets you skip optional parameters. - Overloading: several methods may share a name if their parameter lists differ. The compiler picks the best match from the argument types.
params: the last parameter can accept any number of arguments, which arrive as an array.out: the method must assign the parameter, and the caller receives it as an extra result. This is theTryParsepattern: returnboolfor success and the value throughout.ref: the method works on the caller’s variable itself and can change it.
A method whose body is a single expression can use => instead of braces and return.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Console.WriteLine(OrderMath.LineTotal(19.99m, 3));Console.WriteLine(OrderMath.LineTotal(19.99m)); // quantity uses its default value 1Console.WriteLine(OrderMath.LineTotal(unitPrice: 5m, quantity: 4)); // named argumentsConsole.WriteLine(OrderMath.ApplyDiscount(100m, 15)); // int overloadConsole.WriteLine(OrderMath.ApplyDiscount(100m, 0.15m)); // decimal overloadConsole.WriteLine(OrderMath.SumOfLines(10m, 20m, 30.50m)); // params: any number of arguments
if (OrderMath.TryParseQuantity("4", out int quantity)) // out: a second result{ Console.WriteLine($"Parsed quantity {quantity}");}Console.WriteLine(OrderMath.TryParseQuantity("four", out _)); // discard the out value
int reserved = 2;OrderMath.Reserve(ref reserved, 3); // ref: the method changes the caller's variableConsole.WriteLine($"Reserved: {reserved}");
var basket = new List<string> { "CABLE-01" };OrderMath.AddFreeGift(basket); // a reference type: the method sees the same listConsole.WriteLine(string.Join(", ", basket));
static class OrderMath{ // A method has a return type, a name and a parameter list; => is an expression body public static decimal LineTotal(decimal unitPrice, int quantity = 1) => unitPrice * quantity;
// Overloads: same name, different parameter types public static decimal ApplyDiscount(decimal amount, int percent) => amount - amount * percent / 100; public static decimal ApplyDiscount(decimal amount, decimal rate) => amount - amount * rate;
public static decimal SumOfLines(params decimal[] lines) { decimal sum = 0m; foreach (decimal line in lines) { sum += line; } return sum; }
public static bool TryParseQuantity(string text, out int quantity) => int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out quantity) && quantity > 0;
public static void Reserve(ref int reservedCount, int extra) => reservedCount += extra;
public static void AddFreeGift(List<string> items) { items.Add("STICKER-00"); // visible to the caller: same list object items = new List<string>(); // NOT visible: only the local copy of the reference changes }}Output:
59.9719.99208585.0060.50Parsed quantity 4FalseReserved: 5CABLE-01, STICKER-00Arguments are passed by value unless you say ref, out or in. For a value type that means the method gets a copy. For a reference type such as List<string>, the copied value is a reference, so the method and the caller see the same list: items.Add is visible to the caller, but items = new List<string>() only redirects the method’s own copy. That is why AddFreeGift adds the sticker yet the caller’s list is not replaced.
Notice that the two ApplyDiscount overloads produce 85 and 85.00. A decimal remembers how many decimal places its calculation produced; format the value (for example {total:0.00}) when the display matters.
Why are these methods inside a class rather than written as local functions after the top-level statements? Local functions cannot be overloaded: declaring two local functions named ApplyDiscount fails with CS0128. Local functions are useful for small helpers that only one method needs; the methods and lambdas hub covers them along with out variables, extension methods and params collections.
Exceptions
Section titled “Exceptions”An exception is how .NET reports that an operation could not complete: a string that is not a number, a division by zero, a file that does not exist. When code throws an exception, the runtime unwinds the call stack looking for a matching catch block. If none matches, the program stops with the exception message and stack trace.
trywraps code that might throw.catch (SomeException ex)handles one type of exception and anything derived from it. The runtime checkscatchblocks top to bottom and runs the first that matches, so put specific types before general ones; the compiler rejects acatch (FormatException)that follows acatch (Exception)with CS0160.catch (...) when (condition)is an exception filter (C# 6): the block only handles the exception when the condition is true.finallyalways runs, whether thetryblock finished normally, threw, or returned early. Use it for cleanup.throw new SomeException("message")raises an exception; inside acatchblock,throw;on its own rethrows the current exception.
Custom exception types derive from Exception and add the data a handler needs, like Requested below.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
string[] inputs = { "3", "abc", "0", "-2" };
foreach (string input in inputs){ try { int boxes = int.Parse(input); // FormatException for "abc" decimal perBox = 60m / boxes; // DivideByZeroException for 0 Console.WriteLine($"{input}: {Reserve(boxes)}, {perBox:0.00} per box"); } catch (FormatException) { Console.WriteLine($"{input}: not a number"); } catch (DivideByZeroException ex) { Console.WriteLine($"{input}: {ex.Message}"); } catch (OutOfStockException ex) when (ex.Requested < 0) // exception filter (C# 6) { Console.WriteLine($"{input}: invalid request ({ex.Message})"); } finally { Console.WriteLine(" checked"); // runs whether or not an exception was thrown }}
// The usual alternative for user input: no exception at allConsole.WriteLine(int.TryParse("abc", out int value) ? $"Parsed {value}" : "TryParse returned false");
try{ ProcessOrder();}catch (InvalidOperationException ex){ Console.WriteLine($"Caller saw: {ex.Message}");}
static string Reserve(int boxes){ if (boxes < 0) { throw new OutOfStockException(boxes, "quantity cannot be negative"); } return $"reserved {boxes}";}
static void ProcessOrder(){ try { throw new InvalidOperationException("payment gateway timeout"); } catch (InvalidOperationException ex) { Console.WriteLine($"Logging: {ex.Message}"); throw; // rethrow and keep the original stack trace }}
public class OutOfStockException : Exception{ public OutOfStockException(int requested, string message) : base(message) { Requested = requested; }
public int Requested { get; }}Output:
3: reserved 3, 20.00 per box checkedabc: not a number checked0: Attempted to divide by zero. checked-2: invalid request (quantity cannot be negative) checkedTryParse returned falseLogging: payment gateway timeoutCaller saw: payment gateway timeoutThree habits keep exception handling healthy:
- Rethrow with
throw;, notthrow ex;.throw ex;resets the stack trace to thecatchblock, so the log no longer shows where the error started. - Do not use exceptions for expected input problems. User input that might not be a number is normal;
int.TryParsereports it with abooland costs far less than throwing and catching. - Catch only what you can handle. A
catch (Exception)that logs and continues hides real bugs. Catch specific types close to where you can do something useful, and let the rest reach a top-level handler.
Complete working result
Section titled “Complete working result”The checkout program below combines the three sections. ParseLine throws FormatException for malformed lines, the loop catches it per line so one bad line does not stop the others, PriceLine uses a default parameter and the conditional operator for the bulk discount, and ShippingClass is an expression-bodied method built on a switch expression. ParseLine returns two values as a tuple, and (string sku, int quantity) = ... deconstructs it into two variables; the types and records hub covers tuples.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
string[] orderLines = { "CABLE-01;3", "MOUSE-02;x", "DOCK-03;0", "HUB-04;12" };decimal grandTotal = 0m;int rejected = 0;
foreach (string line in orderLines){ try { (string sku, int quantity) = Checkout.ParseLine(line); decimal total = Checkout.PriceLine(sku, quantity); grandTotal += total; Console.WriteLine($"{sku,-9} x{quantity,3} = {total,8:0.00} ({Checkout.ShippingClass(quantity)})"); } catch (FormatException ex) { rejected++; Console.WriteLine($"Rejected '{line}': {ex.Message}"); }}
Console.WriteLine($"Accepted total: {grandTotal:0.00}, rejected lines: {rejected}");
static class Checkout{ private const decimal UnitPrice = 9.99m;
public static (string Sku, int Quantity) ParseLine(string line) { string[] parts = line.Split(';'); if (parts.Length != 2 || !int.TryParse(parts[1], out int quantity)) { throw new FormatException("expected SKU;quantity"); } if (quantity <= 0) { throw new FormatException("quantity must be at least 1"); } return (parts[0], quantity); }
public static decimal PriceLine(string sku, int quantity, decimal discountRate = 0m) { decimal rate = quantity >= 10 ? 0.05m : discountRate; // bulk discount return Math.Round(UnitPrice * quantity * (1 - rate), 2); }
public static string ShippingClass(int quantity) => quantity switch { 1 => "letter post", <= 5 => "small parcel", _ => "freight", };}Output:
CABLE-01 x 3 = 29.97 (small parcel)Rejected 'MOUSE-02;x': expected SKU;quantityRejected 'DOCK-03;0': quantity must be at least 1HUB-04 x 12 = 113.89 (freight)Accepted total: 143.86, rejected lines: 2Add a line such as "CASE-05;-1" or "NOTE" and predict which message appears before you run it.
Troubleshooting
Section titled “Troubleshooting”Exact messages from the .NET 10 SDK compiler:
| Error | Cause | Fix |
|---|---|---|
CS0163: Control cannot fall through from one case label ('case 1:') to another |
A switch section without break, return, throw or goto case. |
End the section with break, or stack the labels with no code between them. |
warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). |
A switch expression has no arm for some inputs; at run time an unmatched value throws SwitchExpressionException. |
Add a _ => arm, or throw a meaningful exception from it. |
CS0161: 'F(int)': not all code paths return a value |
A non-void method can reach its end without return. |
Add a return (or throw) on every path. |
CS0177: The out parameter 'y' must be assigned to before control leaves the current method |
An out parameter is not set on some path. |
Assign it on every path, even the failure path (quantity = 0;). |
CS1503: Argument 1: cannot convert from 'string' to 'int' |
No overload accepts the argument types you passed. | Convert the argument, or check which overloads exist. |
CS0128: A local variable or function named 'ApplyDiscount' is already defined in this scope |
Two local functions with the same name: local functions cannot be overloaded. | Move the methods into a class, or give them different names. |
CS0160: A previous catch clause already catches all exceptions of this or of a super type ('Exception') |
A general catch comes before a more specific one. |
Order catch blocks from most specific to most general. |
Check your understanding
Section titled “Check your understanding”- Can one
switchsection fall through into the next in C#? No. Every non-empty section must end with a jump such asbreak; the compiler reports CS0163 otherwise. Empty stacked labels share one section. - When do you pick a
switchexpression over aswitchstatement? When every branch only produces a value. The expression is shorter, cannot fall through, and the compiler warns when inputs are not covered. - A method receives a
List<string>and assigns a new list to its parameter. Does the caller see the new list? No. The reference is passed by value, so reassigning the parameter only changes the method’s copy. CallingAddon the original list is visible, because both copies point at the same object. - What is the difference between
throw;andthrow ex;in acatchblock?throw;rethrows the same exception with its original stack trace.throw ex;resets the trace to the current line, which hides where the problem began. - When does
finallyrun? Always: after a normal finish, after an exception (caught or not), and after an earlyreturn.
Next steps
Section titled “Next steps”Continue with classes and objects, where methods move into your own types alongside data, constructors and access modifiers.
Related pages
Section titled “Related pages”- C# basics overview: the full reading path.
- Control flow and operators hub:
breakandcontinue, labeledbreakandcontinue, throw expressions and checked arithmetic. - Pattern matching hub: every pattern you can use in
isandswitch. - Methods and lambdas hub: local functions,
outvariables,nameof, extension methods andparamscollections. - Async and await hub: exceptions in asynchronous code.
Official references
Section titled “Official references”- Selection statements: if and switch
- Iteration statements: for, foreach, do and while
- Jump statements: break, continue, return and goto
- The switch expression
- Methods in C# and method parameters
- Named and optional arguments
- Exception-handling statements: throw, try-catch and try-finally
- Best practices for exceptions