🚀 C# Tip — Relational Pattern Matching
Relational pattern matching is one of those C# features that quietly removes noise from your code.
No more long if/else chains.
No more unreadable boundary checks.
Just clear, declarative intent.
🧠 What Is Relational Pattern Matching?
Relational patterns let you compare values using operators directly inside pattern matching:
< > <= >=
They are commonly used with switch expressions and is patterns.
✍️ Before vs After
❌ Traditional if / else
if (age < 18) category = "Minor"; else if (age <= 65) category = "Adult"; else category = "Senior";
✅ Relational pattern matching
var category = age switch { < 18 => "Minor", <= 65 => "Adult", _ => "Senior" };
Same logic.
Far more readable.
🎯 Real-World Examples
1️⃣ Input Validation
if (quantity is <= 0) throw new ArgumentException("Quantity must be positive");
Clear intent. No magic numbers hidden in conditions.
2️⃣ Pricing & Business Rules
var discount = total switch { < 100 => 0m, >= 100 and < 500 => 0.05m, >= 500 => 0.10m };
Perfect for business thresholds and rules engines.
3️⃣ HTTP Status Classification
var category = statusCode switch { >= 200 and < 300 => "Success", >= 400 and < 500 => "Client Error", >= 500 => "Server Error", _ => "Unknown" };
This reads almost like documentation.
4️⃣ Guard Clauses
if (timeout is < 1 or > 60) throw new ArgumentOutOfRangeException(nameof(timeout));
Short, expressive, and impossible to misread.
5️⃣ Feature Flags & Thresholds
bool isEnabled = loadPercentage switch { < 70 => true, >= 70 and < 90 => allowLimitedMode, _ => false };
No nested logic. No ambiguity.
🧩 Combine with Logical Patterns
Relational patterns really shine when combined with and / or:
if (score is >= 0 and <= 100) { // valid score }
This replaces two comparisons with one readable rule.
⚠️ When Not to Use It
- ❌ Overly complex rules
- ❌ Heavy side effects
- ❌ Logic that needs explanation or comments
If it stops reading like English, extract a method.
🧠 Why This Matters
Relational pattern matching:
- Improves readability
- Reduces bugs at boundaries
- Makes intent explicit
- Turns conditions into rules
Clean code is not fewer lines. It’s clearer decisions.
🎯 Final Takeaway
If your code has:
- Ranges
- Thresholds
- Guards
- Categories
You should be using relational pattern matching.
Once you start, if/else chains will feel… old.
#csharp #dotnet #patternmatching #cleanCode #softwareengineering #backend