C# & CLR Internals (50 Qs)•Part 3: CLR Internals, Native AOT & Production Diagnostics (25 - 35)
Pattern Matching in Modern C# (C# 9 - 12+).
senior LevelCode ExamplecsharpCLR Internals
In Simple Words: Pattern matching tests expressions against shapes, types, and values:
- Property Patterns: Inspects object properties directly without nested null-checks.
- Relational & Logical Patterns: Matches numeric thresholds with
and,or,not,>,<. - List Patterns (C# 11+): Matches elements within arrays or lists (
[var first, .., var last]).
csharp
public decimal CalculateDiscount(Order order) => order switch
{
{ TotalAmount: > 1000, Customer.IsVip: true } => 0.20m, // 20% discount
{ TotalAmount: > 500 } => 0.10m,
{ Items: [.., { IsClearance: true }] } => 0.05m, // List pattern check
_ => 0.0m
};