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

    StructureUse WhenExample
    if / else2-3 conditions, boolean logicAge check, validation
    ternary ? :Simple true/false assignmentStatus = condition ? "A" : "B"
    switch statementMany discrete valuesDay of week, menu options
    switch expressionReturn a value from patternsPrice tiers, classifications
    pattern matchingType checks, range checksObject 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.

    Try it Yourself ยป
    C#
    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.

    Try it Yourself ยป
    C#
    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.

    Try it Yourself ยป
    C#
    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 break in 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. Use StringComparison.OrdinalIgnoreCase when needed.
    • Order of else-if matters: Put the most specific conditions first. if (score >= 60) before if (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 throw SwitchExpressionException if no pattern matches.

    ๐ŸŽ‰ Lesson Complete

    • โœ… if / else if / else handles conditional branching with boolean expressions
    • โœ… Ternary operator ? : for concise single-line conditional assignments
    • โœ… switch statements handle multiple specific values with case and break
    • โœ… 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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service