Intermediate 22 min readModule: Module 3: Object-Oriented Design, Pattern Matching & Interfaces
Modern Pattern Matching & Switch Expressions
Write expressive, concise business logic using C# pattern matching: type patterns, property patterns, positional patterns, relational comparisons, and switch expressions.
What You Will Learn in This Lesson
- The evolution of the switch statement into concise switch expressions (`=>`)
- Property patterns for inspecting nested object states without nested if blocks
- Relational patterns (`> 100`, `<= 500`) and logical combinators (`and`, `or`, `not`)
- Default interface methods for evolving API contracts safely
Introduction & Core Concept
Modern C# has embraced functional pattern matching, transforming the way developers evaluate complex business rules. Instead of long, error-prone chains of 'if-else' statements and type casts, C# switch expressions allow you to match on types, properties, ranges, and positional tuples in clean, declarative expressions.
WHY DOES THIS MATTER IN THE REAL WORLD?
Complex business logic (like discount rules, tax calculations, and permission gates) becomes readable, self-documenting, and provably exhaustive when written with pattern matching switch expressions.
Syntax & Structure
csharp
var status = code switch { 200 => "OK", 404 => "Not Found", >= 500 => "Server Error", _ => "Unknown"};Advanced Property and Relational Pattern Matching in C#
csharpcsharp
1234567891011121314151617181920212223242526272829303132333435363738394041// Modern Pattern Matching & Switch Expressions in C# 13using System;public abstract record PaymentMethod;public record CreditCard(string CardNumber, decimal Balance, bool IsVerified) : PaymentMethod;public record CryptoWallet(string WalletAddress, decimal UsdValue) : PaymentMethod;public record BankTransfer(string AccountNumber, bool IsInternational) : PaymentMethod;public class FeeCalculator{public static decimal CalculateProcessingFee(PaymentMethod payment, decimal amount) =>payment switch{// Property pattern with relational conditions and logical combinatorsCreditCard { IsVerified: true, Balance: >= 1000m } => amount * 0.015m, // 1.5% VIP rateCreditCard { IsVerified: true } => amount * 0.025m, // 2.5% StandardCreditCard { IsVerified: false } => throw new InvalidOperationException("Unverified card rejected."),CryptoWallet { UsdValue: >= 5000m } => 5.00m, // Flat $5 feeCryptoWallet => 15.00m, // Flat $15 feeBankTransfer { IsInternational: true } => 25.00m,BankTransfer { IsInternational: false } => 0.00m, // Free domestic transfer_ => throw new ArgumentException("Unsupported payment provider.")};}public class Program{public static void Main(){PaymentMethod card = new CreditCard("4111222233334444", 2500m, true);PaymentMethod crypto = new CryptoWallet("0x71C...89B", 8000m);PaymentMethod wire = new BankTransfer("ACC-90112", false);Console.WriteLine($"Credit Card Fee (100 USD transaction): USD {FeeCalculator.CalculateProcessingFee(card, 100m)}");Console.WriteLine($"Crypto Wallet Fee (500 USD transaction): USD {FeeCalculator.CalculateProcessingFee(crypto, 500m)}");Console.WriteLine($"Domestic Wire Fee (10,000 USD transaction): USD {FeeCalculator.CalculateProcessingFee(wire, 10000m)}");}}
Line-by-Line Technical Breakdown
1Exhaustiveness Checking: When pattern matching over an enum or closed class hierarchy, the C# compiler validates exhaustiveness. If a developer fails to handle a potential case, the compiler emits a warning, preventing unhandled edge cases.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[CSHARP]
CSHARP SOURCE EDITOR
Interactive Live CodeCommon Mistakes & How to Avoid Them
#1: Writing deeply nested if-else statements with manual (Type) casting instead of switch expressions.
Pattern matching combines type-checking, property inspection, and casting in a single atomic operation.
Incorrect / Antipattern
if (obj is CreditCard) { var card = (CreditCard)obj; if (card.IsVerified) { ... } }Correct / Professional Solution
if (obj is CreditCard { IsVerified: true } card) { ... }Industry Best Practices & Professional Standards
- Use switch expressions (`=>`) for calculation and routing logic over traditional switch statements.
- Use property patterns to inspect complex nested domain models cleanly.
- Combine relational operators (`>`, `<=`) with logical combinators (`and`, `or`, `not`) for clear boundary rules.
Lesson Summary & Core Takeaways
- C# switch expressions deliver concise functional pattern matching.
- Property patterns inspect object state and unpack fields automatically.
- Relational patterns eliminate repetitive boolean logic chains.