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
- Replacing repetitive conditional code
- Checking object shapes and properties
- Handling different runtime types
- Expressing ranges and business rules clearly
đ§ 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 a question
Ask AlgoLassi and get an answer plus the tutorials worth studying next.
đŦ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.