C# & CLR Internals (50 Qs)•Part 2: Concurrency, Zero-Allocation & Advanced Language Features (11 - 24)
How does modern Pattern Matching work in C# (Property, Positional, Relational & List patterns)?
senior LevelCode ExamplecsharpConcurrency
In Simple Words:
Pattern matching tests values against shapes and types cleanly without nested if-else cascades or explicit casting.
csharp
// Relational and Property pattern matching with switch expressions:
decimal CalculateDiscount(Order order) => order switch {
{ Customer.IsVip: true, TotalAmount: > 1000m } => 0.20m,
{ TotalAmount: >= 500m and <= 1000m } => 0.10m,
{ Items: [var single] } => 0.05m, // List pattern!
_ => 0.00m
};
Under the Hood:
The Roslyn compiler compiles switch patterns into jump tables and compact bitwise checks, achieving $O(1)$ dispatch time.