Immutability is a cornerstone of robust distributed systems, but achieving it in C# has historically required copious boilerplate. C# 9.0 introduces Records, a first-class citizen for immutable data. Records provide value-based equality, non-destructive mutation, and concise syntax.
The Syntax Evolution
// Before (Verbose)
public class Person : IEquatable<Person>
{
public string Name { get; }
public int Age { get; }
public Person(string name, int age) => (Name, Age) = (name, age);
// + GetHashCode(), Equals(), == operator override...
}
// After (C# 9 Record)
public record Person(string Name, int Age);
Value-Based Equality
Records check equality by properties, not reference.
var p1 = new Person("Alice", 30);
var p2 = new Person("Alice", 30);
Console.WriteLine(p1 == p2); // True! (Unlike classes)
Non-Destructive Mutation (‘with’ expressions)
To modify an immutable object, you create a copy with specific changes.
var p3 = p1 with { Age = 31 };
// p1 remains unchanged. p3 is a new object.
Key Takeaways
- Use **Records** for DTOs, Messages, and Event payloads.
- Records compile to classes with synthesized equality members.
- Records support inheritance, unlike structs.
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.