Phase 7 of 30 · Topic 7.4

Non-Destructive Mutation with `with` Expressions

1Concept

The `with` expression creates a shallow copy of a record while overriding specified properties, preserving immutability in functional domain architectures.

2Architecture Diagram

Original Record:
[ Transaction { Id: 101, Status: "Pending", Amount: 500.0 } ]
       │
   with { Status = "Completed" }
       ▼
New Record Instance (Original remains untouched):
[ Transaction { Id: 101, Status: "Completed", Amount: 500.0 } ]

3Code Example

C# 13 & .NET 9
using System;

public record Transaction(string TxId, decimal Amount, string Status);

public class WithExpressionDemo
{
    public static void Main()
    {
        var txOriginal = new Transaction("TX-9901", 1250.50m, "Pending");
        
        // Non-destructive mutation
        var txApproved = txOriginal with { Status = "Settled" };

        Console.WriteLine($"Original: {txOriginal.TxId} -> {txOriginal.Status}");
        Console.WriteLine($"Mutated:  {txApproved.TxId} -> {txApproved.Status}");
    }
}

4Expected Output

Original: TX-9901 -> Pending
Mutated:  TX-9901 -> Settled

5Key Takeaways

  • `with` expressions work on `record class`, `record struct`, and standard `struct`.
  • Performs shallow copying; deep object references within the record are shared.
  • Essential for event-sourcing and Redux-like immutable state machines.