Records, Structs & Pattern Matching

Records, Structs & Pattern Matching in .NET: Modern C# provides advanced features for functional programming, domain-driven design, and immutable data modeling…

Modern C# provides advanced features for functional programming, domain-driven design, and immutable data modeling without verbose boilerplate.


1. Records: The Power of Immutability & Value Semantics

In standard C# classes, equality is based on reference (two instances are equal only if they point to the exact same memory address on the heap).

Records (record class or record struct) are immutable reference types with built-in value-based equality. Two record instances with identical property values evaluate to true when compared with ==.

Positional Record Syntax:

// Generates constructor, properties, Equals(), GetHashCode(), and ToString() in one line!
public record UserProfile(Guid Id, string Username, string Email, bool IsVerified);

// Instantiation
var user1 = new UserProfile(Guid.NewGuid(), "alex_dev", "alex@codeacademix.dev", true);
var user2 = user1 with { }; // Exact shallow clone

// Value-based equality comparison:
Console.WriteLine(user1 == user2); // Outputs: True!

// Non-destructive mutation with 'with' expression:
var updatedUser = user1 with { Email = "alex.lead@codeacademix.dev" };
Console.WriteLine(user1.Email);       // alex@codeacademix.dev (Original unchanged!)
Console.WriteLine(updatedUser.Email); // alex.lead@codeacademix.dev

2. Advanced Pattern Matching

Pattern matching allows expressive, high-speed structural inspection of object shapes, property constraints, and types without repetitive if-else or casting code.

Pattern Matching in Action:

public abstract record PaymentTransaction;
public record CreditCard(string CardNumber, decimal Limit, decimal CurrentBalance) : PaymentTransaction;
public record BankTransfer(string Iban, bool IsVerified) : PaymentTransaction;
public record CryptoWallet(string WalletAddress, decimal GasFeeGwei) : PaymentTransaction;

public static class PaymentProcessor
{
    public static string EvaluatePayment(PaymentTransaction transaction, decimal chargeAmount) => transaction switch
    {
        // Property pattern with relational guard clause:
        CreditCard { CurrentBalance: var balance, Limit: var limit } when (balance + chargeAmount) <= limit =>
            $"Payment approved. New balance: {(balance + chargeAmount):C}",

        CreditCard => "Payment rejected: Exceeds card credit limit.",

        // Positional / property matching on booleans:
        BankTransfer { IsVerified: true } => "ACH Transfer scheduled for next banking business day.",
        BankTransfer => "Payment rejected: Bank account must be verified before transfer.",

        // Relational pattern (<, <=, >, >=):
        CryptoWallet { GasFeeGwei: > 100m } => "Gas fee exceeds threshold. Transaction postponed.",
        CryptoWallet wallet => $"Broadcasting transaction to wallet {wallet.WalletAddress[..6]}...",

        null => throw new ArgumentNullException(nameof(transaction)),
        _ => "Unsupported payment gateway transaction type."
    };
}

3. Positional Deconstruction

Records support automatic tuple deconstruction:

var (id, username, email, isVerified) = user1;
Console.WriteLine($"User {username} has email {email}");