Should a C# team model domain entities such as Customer as record classes, or keep records for values like Money and Address?
answer
- identity versus data
- equality on every field
- set accessors and hash keys
- ToString prints personal data
- snapshots are values
basics
~20 sKeep record classes for values whose identity is their data, such as Money, Address, messages and query results, and model entities with identity and a lifecycle as classes, because the generated equality and printing assume the data is the identity.
solid answer
~40 sA record's generated members encode one claim: two instances with equal fields are the same thing. That holds for `Money` and `Address` and fails for a `Customer`, whose identity is its `Id` while its name and email change. As a record, two snapshots of one customer compare unequal once any field differs, a record with `set` accessors changes its hash while it sits in a `HashSet<T>`, and the generated `ToString` prints the email into logs. You can declare `Equals(Customer?)` and `GetHashCode` over `Id`, but then you keep little of what made it a record, and the printing and hierarchy rules still need overrides. My default rule: sealed, positional, init-only records for values, messages and snapshots; classes with explicit identity for entities; exceptions reviewed case by case.
code
csharp · 13 linesvar seen = new HashSet<ShippingAddress>();
var home = new ShippingAddress { City = "Lyon", Street = "12 Rue X" };
seen.Add(home);
home.Street = "14 Rue X"; // set accessor: the hash code changes
Console.WriteLine(seen.Contains(home)); // False: looked up in the wrong bucket
Console.WriteLine(seen.Count); // 1: the element is still stored
public record ShippingAddress
{
public string City { get; set; } = "";
public string Street { get; set; } = "";
}go deeper
Know that records compare by value and ordinary classes by reference, and that this difference decides which one fits a type.
Explain mechanically what goes wrong when an entity is a record: equality over every field, hash drift with set accessors, and ToString printing everything.
Find the bugs this causes in a real codebase, such as stranded set entries, missed dictionary lookups and personal data in logs, and propose the narrowest fix for each.
Own the rule: where records are the default, where classes are, how exceptions get reviewed, and how the rule is written down so it survives team turnover.
## What a record promises A record class is the compiler writing a specific contract for you. Its synthesized `Equals`, `GetHashCode`, `==` and `!=` treat two instances as the same when their run-time types match and every field is equal; its `ToString` prints every public member; its copy members support nondestructive updates. Each of those is the right behavior for a **value**: an amount of money, an address, a date range, a message on a queue, a row returned by a query. None of them is the right default for an **entity**: something with an identity that persists while its attributes change, such as a customer, an order or an account. The decision is therefore not about syntax or brevity. It is whether the type's identity is its data. ## Where an entity collides with the generated members | Concern | Value record (`Money`) | Entity as a record (`Customer`) | |---|---|---| | Equality | equal amounts and currencies are interchangeable | two loads of customer 7 compare unequal after an email change, though they are one customer | | Hashing | stable, because properties are init-only | a record with `set` accessors changes its hash while stored in a set or used as a dictionary key | | `ToString` | harmless | prints email, phone and address into every log line that formats it | | Inheritance | rarely used | a premium tier as a derived record is never equal to the base, by `EqualityContract` | | Copying | `with` gives a new value | `with` gives a second object claiming the same `Id` | The hashing row is the most expensive in production. A `HashSet<T>` stores an element in a bucket chosen by its hash at insertion time. Change a property on a mutable record afterwards and `Contains` on the very same instance returns `false`, while `Count` still includes it: the entry is stranded, not removed. ## The options a team actually has 1. **Classes for entities, records for values.** The entity keeps reference equality or an explicit `Id` comparison, its own `ToString`, and methods that guard its invariants. `Money`, `Address`, events and query results are records. 2. **Records with identity-based equality.** Declare `Equals(Customer?)` and `GetHashCode` over `Id`. This works, but the record now needs a hand-written `PrintMembers` to keep personal data out of logs, and across a record hierarchy the derived record's sealed `Equals(Customer?)` still casts with `as`, so `Id`-only equality between a base and a derived instance holds in one direction only. 3. **Immutable snapshots.** Treat each `Customer` record instance as a snapshot of the entity at one moment: never mutate it, never use it as a key, compare by `Id` explicitly where identity matters. This suits read models and messages, and fits records well, because a snapshot really is a value. ## A rule set to adopt - Declare records **`sealed`** unless a hierarchy is needed, since `EqualityContract` makes subtypes unequal. - Keep record properties **init-only**; a `set` accessor on a record needs a reviewer's sign-off. - A record with a **collection member** that takes part in equality declares its own `Equals` and `GetHashCode`, with tests. - A record carrying **personal or secret data** declares `PrintMembers` to mask it. - **Entities** with identity and a lifecycle are classes; a record named after an entity is a snapshot or a message, and its name says so (`CustomerSnapshot`, `CustomerRegistered`). ## Costs and counter-arguments - **Boilerplate.** Classes for entities need constructors and properties written out; primary constructors on classes reduce that, without the record's equality. - **Equality cost.** Generated equality visits every field; large records compared often, or used as keys, pay for that on every lookup. - **Frameworks.** Microsoft's C# documentation notes that Entity Framework Core relies on reference equality to keep one instance per entity, and calls records unsuitable as its entity types; that mapping question belongs to EF Core's own material. - **Teams that prefer immutable domain models** can choose option 3 consistently and get real benefits, provided nobody puts a mutable record in a hash-based collection. ## How to answer in an interview Frame it as identity versus data, name the concrete failure modes (equality on every field, hash drift with `set` accessors, personal data in `ToString`, unequal subtypes), give your default rule and its exceptions, and show you know option 2 exists and why it erodes most of the record's value.
- If a team keeps Customer as a C# record but declares equality over Id, what still causes trouble?The generated `ToString` still prints every public member, email included, until `PrintMembers` is replaced. A `with` expression still makes a second object with the same `Id` that now compares equal to the original though its data differs. In a record hierarchy, the derived record's sealed `Equals(Customer?)` still casts with `as`, so base-to-derived `Id` equality holds in one direction only. Each needs another hand-written override.
- When is a C# record the right choice for something that carries an Id?When the instance is a snapshot or a message rather than the live entity: a `CustomerRegistered` event, a `CustomerSummary` returned from a query, a cache entry. There the data at that moment is the value, so equality over all fields is correct, and the record's init-only properties match the fact that a snapshot never changes.
- Records are just shorter classes, so every domain type should be one.
- Naming a positional parameter Id makes the record compare by Id.
- Settable record properties are harmless because equality still works.
- The generated ToString of any record is safe to log.
- Record classes are value types, so they avoid allocations for entities.