Control Flow

By the end of this lesson you'll be able to make your programs decide — branching with if / else , picking from many options with switch , and matching ranges and types with pattern matching. This is what turns a fixed list of instructions into a program that reacts.

Part of the free C# course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

What You'll Learn

💡 Real-World Analogy

Control flow is like a railway switching station . A train (your program) arrives at a junction and the switch operator (your condition) sends it down one of several tracks. An if-else is a simple fork: left or right. A switch is a complex junction with many possible tracks. Pattern matching is the automated system that reads the cargo's type and weight to route it to exactly the right platform. Without control flow, the train can only ever roll straight ahead.

📊 Control Flow Quick Reference

Structure

Use When

Example

if / else

2-3 conditions, boolean logic

Age check, validation

ternary ? :

Simple true/false choice

cond ? "A" : "B"

switch statement

Many discrete values

Day of week, menu options

switch expression

Return a value from patterns

Price tiers, classifications

pattern matching

Type checks, range checks

Object classification

1. If, Else-If, and Else

The if statement runs a block of code only when its condition is true . Add else if for more checks and a final else as a catch-all. The key rule: the chain is read top to bottom and the first true branch wins — the rest are skipped. For a simple two-way choice, the ternary operator ( condition ? a : b ) does it in one line. Read this worked example and run it first.

Your turn. The classifier below is almost complete — fill in the four blanks marked ___ using the hints. Remember branches are checked top to bottom, so the conditions must go from smallest range upward.

2. Switch Statements & Expressions

Reach for switch when one value can take many specific forms. The traditional switch statement lists each case and needs a break to end it. The modern C# 8+ switch expression is tidier — it returns a value with the => arrow, needs no break , and supports relational patterns like >= 3 and <= 5 . Use _ (the discard) as the catch-all.

Now you try. Complete the traffic-light switch expression below by filling in the two blanks — one quoted action and the discard pattern that catches anything unexpected.

3. Pattern Matching

Pattern matching is one of C#'s most powerful features. A switch expression can match on value ranges (relational patterns like < 5 ), on types (type patterns like obj is string s ), and you can attach an extra when guard for fine-grained checks. It replaces tangled if-else chains with clean, declarative code that the compiler can even check for completeness.

Putting It Together: a Cinema Entry Desk

Here's a small but real program that uses everything from this lesson at once — an if / else if chain to choose an age band, a switch expression to map that band to a price, a ternary for the VIP surcharge, and || to decide admission. Read it line by line; you understand every part now.

This is the shape of nearly all real logic: a few branches pick a category, a mapping turns that category into a value, and a final condition decides the outcome.

Common Errors (and the fix)

Pro Tips

Frequently Asked Questions

Q: When should I use a switch instead of if / else if ?

Use switch when you're checking one value against many specific options (a day number, a status string, an age band). Use if / else if when conditions are unrelated or combine several variables with && and || .

Q: What's the difference between a switch statement and a switch expression ?

A statement does something in each case (and needs break ). An expression returns a value using the => arrow and is assigned to a variable: string s = day switch { ... } ; . The expression form is the modern default for mapping input to output.

Not for an if — it can run nothing if no branch matches. But a switch expression should always have a _ arm, otherwise it throws SwitchExpressionException when nothing matches.

Q: Why did my code assign instead of compare?

You wrote = (assignment) where you meant == (equality). In C# a condition must be a bool , so if (x = 5) is a compile error — a helpful reminder to use == .

📋 Quick Reference

Task

Code

Notes

Branch

if (x > 0) { ... } else { ... }

First true block runs

One-line choice

var s = ok ? "Y" : "N";

Ternary operator

Multi-case

switch (d) { case 1: ...; break; }

Needs break

Return a value

var n = d switch { 1 => "Mon", _ => "?" } ;

No break; needs _

Range pattern

>= 18 and < 65 => "Adult"

Relational + and/or

Type pattern

obj is string s

Test type + cast

Mini-Challenge: FizzBuzz

No blanks this time — just a brief and an outline. FizzBuzz is the classic control-flow exercise (and a real interview question): loop 1 to 15, and for each number print "Fizz", "Buzz", "FizzBuzz", or the number itself. The trick is checking the "both" case first . Build it, run it, and match the expected output in the comments.

🎉 Lesson Complete

Practice quiz

In an if / else if / else chain, which branch runs?

  • All matching branches
  • The last matching branch
  • The first branch whose condition is true
  • A random branch

Answer: The first branch whose condition is true. The chain is checked top to bottom and the FIRST true branch wins; the rest are skipped.

In a traditional switch STATEMENT, what must end each non-empty case?

  • break (or return)
  • A semicolon only
  • continue
  • Nothing

Answer: break (or return). C# does not allow silent fall-through, so each non-empty case needs break or return.

What does a switch EXPRESSION use as its catch-all (default) pattern?

  • default:
  • else
  • *
  • _

Answer: _. The discard pattern _ matches anything in a switch expression, acting as the catch-all.

Which arrow does a switch expression use to map a pattern to a result?

  • ->
  • =>
  • :
  • ==

Answer: =>. Switch expressions use the => arrow, e.g. day switch { 1 => "Mon", _ => "?" }.

What does the relational pattern >= 3 and <= 5 match?

  • Values from 3 to 5 inclusive
  • Exactly 3 or 5
  • Any value below 3
  • Only 4

Answer: Values from 3 to 5 inclusive. It combines two relational patterns with 'and', matching values in the range 3 to 5 inclusive.

What does the type pattern obj is string s do?

  • Always throws
  • Converts obj to a string
  • Tests if obj is a string AND casts it to s in one step
  • Compares obj to "string"

Answer: Tests if obj is a string AND casts it to s in one step. It checks the runtime type and, if it matches, assigns the cast value to s — test and cast in one step.

What happens if a switch expression has no matching arm and no _ ?

  • It returns null
  • It throws a SwitchExpressionException at runtime
  • It returns 0
  • It skips silently

Answer: It throws a SwitchExpressionException at runtime. Without a matching pattern or a _ catch-all, a switch expression throws SwitchExpressionException.

Why must if (age < 13) come before if (age < 65) in a top-down chain?

  • Alphabetical order
  • It does not matter
  • To avoid a syntax error
  • Otherwise the broader condition matches first and the narrower one becomes unreachable

Answer: Otherwise the broader condition matches first and the narrower one becomes unreachable. Branches are checked top to bottom; ordering from smallest range upward keeps each branch reachable.

What is the ternary operator best used for?

  • Looping
  • Choosing a value in one short expression
  • Defining a method
  • Declaring a class

Answer: Choosing a value in one short expression. The ternary condition ? a : b is a one-line if/else that produces a value.

When is a switch generally preferred over a long if/else if chain?

  • Never
  • When combining unrelated variables
  • When checking one value against many specific options
  • Only inside loops

Answer: When checking one value against many specific options. switch shines when one value is matched against many discrete options, like a day number or status string.

Continue this course