C# Pattern Matching with switch: A Practical Guide

Modern C# pattern matching lets you express branching logic more clearly than long chains of if statements. It can inspect values, types, properties, and ranges.


🔀 Basic switch Expression

string GetLevel(int score) => score switch
{
    >= 90 => "Excellent",
    >= 75 => "Good",
    >= 50 => "Pass",
    _ => "Fail"
};

The _ pattern acts as the fallback case.


đŸˇī¸ Type Patterns

if (value is string text)
{
    Console.WriteLine(text.Length);
}

The pattern both checks the type and gives you a strongly typed variable.


🔎 Property Patterns

if (customer is { IsActive: true, Age: >= 18 })
{
    // Eligible customer
}

This is useful when a decision depends on several properties of an object.


📊 Relational Patterns

string Classify(int value) => value switch
{
    < 0 => "Negative",
    0 => "Zero",
    > 0 => "Positive"
};

🧩 When Pattern Matching Helps


🧠 Key Takeaway

Pattern matching makes many C# decisions declarative, readable, and easier to extend.

Explore more at đŸ’ģ C# Tutorials.

🤖 AlgoLassi Assistant Have a question about this tutorial?

Ask AlgoLassi and get an answer plus the tutorials worth studying next.

Ask a question

đŸ’Ŧ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.