Conditionals, Pattern Matching & Switch Expressions Masterclass

โšก C# 12 & .NET 8 ๐ŸŸข Chapter 9 of 35 ๐Ÿ“‚ Phase 4: Conditions & Loops ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: if-else Ladders ยท Nested Conditions ยท Switch Statements ยท Switch Expressions (=>) ยท Discard Pattern (_) ยท Guard Clauses (when) ยท Relational Patterns

Welcome to Phase 4 (Chapter 9): C# Conditionals, Pattern Matching & Switch Expressions Masterclass! Conditional logic allows programs to branch execution dynamically based on runtime data. In this chapter, we cover if, else if, else, nested conditions, ternary operator, pattern matching, traditional switch statements, and modern C# 8+ Switch Expressions with relational patterns and guard clauses (when).

1if, else if, else Ladders & Guard Clauses
C# โ€” if-else Ladder Example โ–ถ Run in Compiler
int marks = 78;

if (marks >= 90)
{
    Console.WriteLine("Grade A - Excellent!");
}
else if (marks >= 60)
{
    Console.WriteLine("Grade B - First Class");
}
else if (marks >= 40)
{
    Console.WriteLine("Grade C - Pass");
}
else
{
    Console.WriteLine("Fail - Needs Improvement");
}
2Modern C# Switch Expressions & Pattern Matching

C# 8+ introduced Switch Expressions, which replace verbose switch statements with lightweight, expression-bodied pattern matching:

C# โ€” Switch Expressions & Relational Patterns โ–ถ Run in Compiler
int score = 85;

// C# 8+ Switch Expression (returns a value directly!)
string grade = score switch
{
    >= 90 => "A+",
    >= 80 => "A",
    >= 70 => "B",
    >= 60 => "C",
    _     => "F"  // _ is the discard pattern (default case)
};

Console.WriteLine($"Score {score} -> Grade: {grade}");

// Switch Expression with Tuple Pattern Matching & Guard Clauses
int age = 20;
bool hasTicket = true;

string accessResult = (age, hasTicket) switch
{
    ( >= 18, true ) => "Access Granted - Enjoy the event!",
    ( >= 18, false) => "Access Denied - Ticket required.",
    _               => "Access Denied - Minimum age is 18."
};

Console.WriteLine($"Result: {accessResult}");
3Technical FAQs

Q1: What is the discard pattern '_' in switch expressions?

The underscore _ matches any value. It acts as the default fallback case in switch expressions.

Q2: What are relational patterns in C# 9+?

Relational patterns allow using relational operators like >, <=, >= directly inside switch patterns (e.g., >= 90 => "A").