Control Flow
Lesson 4 โข Beginner Track
What You'll Learn
- Write if, else-if, and else statements to make decisions in your code
- Use the ternary operator for concise one-line conditional assignments
- Build switch statements for handling multiple specific cases
- Use modern switch expressions with pattern matching (C# 8+)
- Apply relational patterns (< 5, >= 18) and combinators (and, or) in switch
- Classify objects by type using pattern matching with the is and switch keywords
๐ก 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 statement is a complex junction with many possible tracks. Pattern matching is like an automated system that reads the cargo type and weight to decide which platform to route it to.
๐ Control Flow Quick Reference
| Structure | Use When | Example |
|---|---|---|
| if / else | 2-3 conditions, boolean logic | Age check, validation |
| ternary ? : | Simple true/false assignment | Status = condition ? "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 evaluates a boolean condition. If true, the code block runs. Use else if for additional checks and else as a catch-all. For simple true/false assignments, the ternary operator (condition ? a : b) is more concise.
If-Else Statements
Grade a score and check multiple conditions.
using System;
class Program
{
static void Main()
{
int score = 85;
// If-else if-else chain
if (score >= 90)
{
Console.WriteLine("Grade: A โ Excellent!");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B โ Great job!");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C โ Good effort");
}
else if (score >= 60)
{
Console.WriteLin
...2. Switch Statements & Expressions
Use switch when you have many specific values to check. The traditional switch statement uses case and break. Modern C# 8+ switch expressions are more concise โ they return a value directly and support relational patterns like >= 5 and < 18.
Switch Statement & Expression
Compare traditional switch with modern switch expressions.
using System;
class Program
{
static void Main()
{
// Traditional switch statement
int day = 3;
switch (day)
{
case 1: Console.WriteLine("Monday"); break;
case 2: Console.WriteLine("Tuesday"); break;
case 3: Console.WriteLine("Wednesday"); break;
case 4: Console.WriteLine("Thursday"); break;
case 5: Console.WriteLine("Friday"); break;
case 6:
case 7: Console.WriteLine("Wee
...3. Pattern Matching
Pattern matching is one of C#'s most powerful features. You can match on value ranges (relational patterns), types (type patterns), and even object properties (property patterns). This replaces complex if-else chains with clean, declarative code.
Pattern Matching
Use relational patterns and type matching to classify data.
using System;
class Program
{
static string GetTicketPrice(int age) => age switch
{
< 5 => "Free",
>= 5 and < 13 => "ยฃ5 (Child)",
>= 13 and < 18 => "ยฃ8 (Teen)",
>= 18 and < 65 => "ยฃ12 (Adult)",
>= 65 => "ยฃ6 (Senior)",
_ => "Unknown"
};
static string Classify(object obj) => obj switch
{
int n when n > 0 => $"Positive integer: {n}",
int n => $"Non-positive integer: {n}",
string s => $"String of length {s.
...Pro Tips
- ๐ก Prefer switch expressions over if-else chains: When mapping input to output, switch expressions are cleaner and the compiler warns if you miss a case.
- ๐ก Always include a default/discard (_) case: This catches unexpected values and prevents runtime errors.
- ๐ก Use pattern matching with is:
if (obj is string s && s.Length > 5)combines type checking and casting in one step. - ๐ก Avoid deeply nested ifs: Use early returns or guard clauses to reduce nesting and improve readability.
Common Mistakes
- Forgetting break in switch: Unlike JavaScript, C# requires
breakin each case (unless cases are stacked intentionally). Missing it causes a compile error. - Using == for strings incorrectly: C# string comparison with
==works correctly (unlike Java), but be aware of case sensitivity. UseStringComparison.OrdinalIgnoreCasewhen needed. - Order of else-if matters: Put the most specific conditions first.
if (score >= 60)beforeif (score >= 90)means 90+ never triggers the A grade. - Empty if blocks:
if (condition) {}compiles but does nothing โ usually a bug. Add a comment if intentional. - Missing exhaustive patterns: Switch expressions without
_will throwSwitchExpressionExceptionif no pattern matches.
๐ Lesson Complete
- โ
if / else if / elsehandles conditional branching with boolean expressions - โ
Ternary operator
? :for concise single-line conditional assignments - โ
switchstatements handle multiple specific values withcaseandbreak - โ
Switch expressions (C# 8+) return values directly with
=>syntax - โ
Relational patterns:
< 5,>= 18 and < 65โ range matching in switch - โ
Type patterns:
obj is string sโ combine type checking and casting - โ Next lesson: Loops โ for, while, do-while, and foreach
Sign up for free to track which lessons you've completed and get learning reminders.