patterncsharpdotnetTip
Records: value equality and with-expressions for immutable data models
Viewed 0 times
C# 9+
record typevalue equalitywith expressionimmutable dtorecord struct csharp
Problem
Classes use reference equality by default, requiring manual Equals/GetHashCode overrides for value-based comparisons. This is boilerplate-heavy and error-prone for data transfer objects and domain value objects.
Solution
Use record types which provide structural equality, ToString, and non-destructive mutation via with:
// Positional record — concise, immutable
public record Point(double X, double Y);
var p1 = new Point(1, 2);
var p2 = new Point(1, 2);
Console.WriteLine(p1 == p2); // true — value equality
// Non-destructive mutation
var p3 = p1 with { Y = 5 }; // new Point(1, 5)
// Mutable record (record class with init)
public record PersonDto
{
public required string Name { get; init; }
public int Age { get; init; }
}
// Record struct — stack-allocated, no inheritance
public readonly record struct Money(decimal Amount, string Currency);Why
Records generate compiler-synthesized Equals, GetHashCode, and == based on all public properties. This eliminates boilerplate for DTOs, value objects, and event payloads where identity is determined by content.
Gotchas
- Records with mutable properties (set not init) still have value equality — can surprise developers
- Inheritance: derived records include base properties in equality but must call base constructor
- Record structs are copied by value — large record structs passed to methods create copies
Revisions (0)
No revisions yet.