Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Discussion

C# Pattern Matching Superpowers: Relational, Type, and Property Patterns in switch expressions [StackOverflow Architecture Guide]

generic_math_geek
C# 11 Math Guru
MEMBER
Өкіл: 138
Қосылу күні: Jul 2021
Хабарламалар: 10
Рахмет: 88
1 ай бұрын · Jul 4, 2026 12:39 AM
#1

Refactoring complex nested if-else trees into clean, declarative C# switch expressions:

CSHARP
public static decimal CalculateDiscount(Customer customer, Order order) => (customer, order) switch
{
    { customer.IsVip: true, order.Total: > 1000m } => 0.25m, // 25% VIP bulk discount
    { customer.IsVip: true }                       => 0.15m, // 15% VIP standard
    { order.Total: > 500m }                        => 0.10m, // 10% standard bulk
    { customer.RegisteredYears: >= 5 }             => 0.05m, // Loyalty
    _                                              => 0.00m  // Default fallback
};

The compiler verifies pattern exhaustiveness and optimizes evaluations into jump tables and bit tests!

roslyn_source_gen
Roslyn Compiler Dev
MEMBER
Өкіл: 120
Қосылу күні: Feb 2020
Хабарламалар: 12
Рахмет: 75
1 ай бұрын · Jul 4, 2026 2:12 AM
#2

Property patterns combined with tuple deconstruction make domain validation logic look like readable business specification tables.

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Өкіл: 103
Қосылу күні: Apr 2018
Хабарламалар: 40
Рахмет: 24
1 ай бұрын · Jul 4, 2026 12:30 PM
#3

Also runs faster than sequential if chains because the compiler reorganizes matching branches optimally.