الانتقال إلى المحتوى
.NETC#· 6 دقائق للقراءة

Records Beyond Immutability: Value Equality, with and Shallow Copies

A record is a class or struct with generated equality and copying. Know what they compare and copy, one level deep.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A search service caches results in a dictionary keyed by 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

The belief: a record is a class whose properties can't change. Write record instead of class, and you get a safe, frozen data object.

It's a reasonable reading of the most common syntax. 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

The 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.

is only a default. Positional properties are init-only in a 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

Two record instances are equal when they have the same runtime type and each data member is equal according to that member's own 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.

The runtime type is part of the comparison too. The compiler generates an 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

A 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.

The copy also takes field values as they are. A property computed once in an initializer isn't recomputed for the copy:

C# Program.cs
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}

Declaring public decimal Gross => Net * (1 + VatRate); computes the value on access, and the copy reports 91.20.

The cache key, before and after

The first tab reproduces both bugs. The second makes the key truly comparable and the filters immutable:

C# Program.cs
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);

Two changes do the work. 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

MythReality
A record is an immutable classIt's a class or struct with generated members; set properties are allowed
Positional properties are always init-onlyThey're read-write in a plain record struct
Records with the same data are equalOnly if every member's own Equals agrees; lists and arrays compare by reference
with creates an independent copyIt's shallow: reference members are shared, initialized values are copied as-is
Records are a good default for entitiesEF Core needs reference equality; use classes for entities

How to apply it in your project

  1. Use records for valuesChoose records for DTOs, messages, query keys and results, where two instances with the same data should be equal. Keep classes for entities with identity.
  2. Check every reference-type memberFor 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 Equals and GetHashCode.
  3. Make immutability realPrefer init-only properties, readonly record struct and immutable collections, so neither a caller nor a with copy can change shared data.
  4. Compute derived values on accessWrite derived properties as expression-bodied members, =>, so with copies always reflect their own data.

Key takeaways

  • record adds generated equality, with, ToString and 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.
  • with makes 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 Equals with GetHashCode when content matters.

📚 المصادر

  1. C# record types — Microsoft Learn
  2. Records (C# reference) — Microsoft Learn
  3. The with expression (C# reference) — Microsoft Learn

التعليقات (0)