Lesson 6/30

Tutorials C# Mastery

Advanced Pattern Matching (Switch Expressions)

On this page

Advanced Pattern Matching

Pattern matching is the most powerful logic evolution in C# history. It allows you to test variables against "shapes" and extract data simultaneously. It has almost entirely replaced the old, bulky switch statements in modern enterprise codebases.

1. The Evolution: Switch Expressions

Instead of the verbose case: and break; syntax, we use a concise, functional-style arrow syntax.

int categoryId = 1;

string categoryName = categoryId switch 
{
    1 => "Electronics",
    2 => "Clothing",
    3 => "Books",
    _ => "Other" // The '_' is the default "discard" pattern
};

2. Relational & Logical Patterns

You can now perform mathematical and logical checks directly inside a switch statement!

var temp = 25;

string status = temp switch 
{
    < 0 => "Freezing",
    >= 0 and <= 20 => "Cold",
    > 20 and < 35 => "Warm",
    >= 35 => "Hot",
    _ => "Unknown"
};

3. Property Pattern Matching

You can "reach inside" an object to check its internal property values without writing nested if statements.

if (user is { IsAdmin: true, IsActive: true }) 
{
    Console.WriteLine("Access Granted!");
}

4. Interview Mastery

Q: "What is the 'is' keyword pattern, and how does it make our code safer during type-casting?"

Architect Answer: "The 'is' pattern combines two steps into one: Type Checking and Variable Assignment. In legacy C#, you had to check if an object was a string, and then cast it: `if (obj is string) { var s = (string)obj; ... }`. This is risky. With Pattern Matching, we write: `if (obj is string message)`. If the check succeeds, C# automatically creates the `message` variable, casts it, and makes it available inside the scope. This eliminates the 'Double-Cast' performance penalty and prevents `InvalidCastException` crashes entirely."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

C# Mastery
Course syllabus
1. Modern C# & Framework Fundamentals
2. Control Flow & Logical Structures
3. Object-Oriented Mastery
4. Functional C# & Collections
5. Asynchronous & Parallel Programming
6. Advanced Engineering & High Performance
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details