0002 C# Records - Immutable Data Modeling

C# records provide a concise way to create immutable reference types with built-in value-based equality.

// Immutable record with init-only properties
public record Person(string Name, int Age)
{
    // Supports non-destructive mutation
    public Person WithName(string newName) => this with { Name = newName };
}

// Usage
var person1 = new Person("Alice", 30);
var person2 = person1 with { Age = 31 }; // Creates a new instance

Key features:

Future topics will cover DateTime, EF Core, SQL, and other advanced .NET concepts.

Is the new Simplified clone/copy with with expression a deep clone or not?

No, the with expression performs a shallow clone. It creates a new instance and copies reference type properties by reference, not creating deep copies.

Example to illustrate:

public record ComplexPerson(string Name, List<string> Hobbies);

var original = new ComplexPerson("Alice", new List<string> { "Reading" });
var clone = original with { Name = "Bob" };

// Modifying hobbies in clone will also affect original
clone.Hobbies.Add("Coding"); 
Console.WriteLine(original.Hobbies.Count); // Still 2, not isolated

For deep cloning, you'll need to manually implement deep copy logic or use serialisation techniques.

When would i ever use that?

Records with with expressions are primarily useful in scenarios requiring:

  1. Immutable Domain Models

public record Order(int Id, decimal Total, DateTime CreatedAt);

// Easy to create modified versions without mutation
var updatedOrder = originalOrder with { Total = 150.00m };
  1. Value Objects in Domain-Driven Design

  1. Creating Configuration Variations

Practical in scenarios valuing immutability, functional programming, and clean object creation patterns.