Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

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 months ago · 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 months ago · 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 months ago · Jul 4, 2026 12:30 PM
#3

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