
Records Beyond Immutability: Value Equality, with and Shallow Copies
- كاتب موثّق
- .NET 10
محتويات المقال
SearchQuery(string Term, List<string> Filters). The team chose a record precisely so that two identical searches would hit the same entry. In production the hit rate is zero and the cache grows with every request. Weeks later a second bug appears: refining a search with query with { Term = "boots" } and adding a filter to the copy also changes the filters of the original query. Both bugs come from the same assumption about what a record is.
The common misconception
record instead of class, and you get a safe, frozen data object.
public record Person(string FirstName, string LastName); really does create init-only properties, so person.FirstName = "x" doesn't compile. Most examples look exactly like that, and the docs describe records as primarily intended for immutable data models. But "primarily intended for" isn't "always," and immutability isn't what makes a record a record.
What actually happens
A record is generated behavior, not a frozen class
record modifier goes on a class or a struct. record alone means record class, a reference type, and record struct is a value type. The modifier tells the compiler to generate members: (Equals, GetHashCode, == and !=), a with copy mechanism, a readable ToString, and a Deconstruct method for positional parameters. Even the generated equality is a real benefit on its own: a plain struct's default Equals relies on reflection, while a record struct gets a generated, faster one.
record class and a readonly record struct, but read-write in a plain record struct. You can also declare { get; set; } properties in any record. Even init-only properties give only shallow immutability: you can't replace the list a property points to, but you can still add items to it.
Equality compares members, one level deep
Equals. For strings, numbers, dates and nested records that's value comparison. For List<T>, arrays and most classes, Equals means reference equality. Two queries with separate lists holding the same filters are therefore different keys, which explains the zero hit rate.
EqualityContract property, so a Student and a Teacher with identical values are never equal, even when both sit in Person variables. And because GetHashCode is computed from the members, a record with settable properties that you change after adding it to a HashSet or as a dictionary key can no longer be found.
with makes a shallow copy
with expression clones the record through a generated copy constructor, then applies your changes. That's a : for a reference-type member, only the reference is copied, so the copy and the original share the same list. In a record class you can declare your own copy constructor to deep-copy such members. A record struct gives you no such hook: with copies it like any assignment, so its reference members are shared the same way.
var price = new Price(100m, 0.14m);var discounted = price with { Net = 80m };Console.WriteLine(discounted.Gross); // 114.00, computed from the old Netpublic record Price(decimal Net, decimal VatRate){ public decimal Gross { get; } = Net * (1 + VatRate); // set once, at creation}public decimal Gross => Net * (1 + VatRate); computes the value on access, and the copy reports 91.20.
The cache key, before and after
var cache = new Dictionary<SearchQuery, int>();cache[new SearchQuery("shoes", ["red", "sale"])] = 42;var again = new SearchQuery("shoes", ["red", "sale"]);Console.WriteLine(cache.ContainsKey(again)); // False: lists compare by referencevar draft = again with { Term = "boots" }; // shallow copy, shared listdraft.Filters.Add("leather");Console.WriteLine($"{again.Filters.Count} vs {draft.Filters.Count}"); // 3 vs 3public record SearchQuery(string Term, List<string> Filters);using System.Collections.Immutable;var cache = new Dictionary<SearchQuery, int>();cache[new SearchQuery("shoes", ["red", "sale"])] = 42;var again = new SearchQuery("shoes", ["red", "sale"]);Console.WriteLine(cache.ContainsKey(again)); // True: compares the itemsvar draft = again with { Term = "boots", Filters = again.Filters.Add("leather") };Console.WriteLine($"{again.Filters.Length} vs {draft.Filters.Length}"); // 2 vs 3public sealed record SearchQuery(string Term, ImmutableArray<string> Filters){ public bool Equals(SearchQuery? other) => other is not null && Term == other.Term && Filters.SequenceEqual(other.Filters); public override int GetHashCode() { var hash = new HashCode(); hash.Add(Term); foreach (var filter in Filters) hash.Add(filter); return hash.ToHashCode(); }}ImmutableArray<string> can't be modified, so Add returns a new array and the original query keeps its two filters. And because ImmutableArray<T> still compares by reference, the record declares its own Equals(SearchQuery?) and GetHashCode, which the compiler allows, to compare the filters item by item. Now the second identical search finds the cached entry.
Myth vs reality
set properties are allowed | |
record struct | |
Equals agrees; lists and arrays compare by reference | |
with creates an independent copy | |
How to apply it in your project
Use records for values Choose records for DTOs, messages, query keys and results, where two instances with the same data should be equal. Keep classes for entities with identity. Check every reference-type member For each list, array or class inside a record, decide what equality should mean. Accept reference equality on purpose, or replace it with an immutable type plus custom EqualsandGetHashCode.Make immutability real Prefer init-only properties, readonly record structand immutable collections, so neither a caller nor awithcopy can change shared data.Compute derived values on access Write derived properties as expression-bodied members, =>, sowithcopies always reflect their own data.
Key takeaways
recordadds generated equality,with,ToStringand deconstruction to a class or struct; immutability is only a default.Equality compares each member with its own Equals, so collections inside records compare by reference.withmakes a shallow copy: lists are shared, and values computed at creation aren't recomputed.Different runtime types are never equal, and mutating a record used as a key breaks lookups. Use records for values, classes for EF Core entities, and override EqualswithGetHashCodewhen content matters.
التعليقات (0)