skip to content

In C#, why do two Address records with the same city and equal List<string> street lines compare unequal, and how do you fix it?

level: middleimportance: must knowfreq 60%

answer

  1. field by field, not deep
  2. the default comparer per field
  3. List<T> keeps reference equality
  4. typed Equals plus GetHashCode

basics

~10 s

A record's synthesized Equals compares each field with EqualityComparer<T>.Default, and List<T> does not override Equals, so two distinct lists compare by reference. Declare Equals(Address? other) using SequenceEqual and a matching GetHashCode.

solid answer

~40 s

Record equality is shallow. The synthesized `Equals(Address?)` checks `EqualityContract` and then calls `EqualityComparer<T>.Default.Equals` on every instance field, including the backing fields of positional properties. For `string` that compares characters; for `List<string>` it falls back to `object.Equals`, which compares references, so two lists holding the same lines make the records unequal and their hash codes almost certainly differ. The fix is to declare `public virtual bool Equals(Address? other)` (non-virtual in a sealed record) that compares the lines with `SequenceEqual`, and a `GetHashCode` that hashes the elements. The compiler keeps generating `Equals(object)`, `==` and `!=`, which now route to your method. Declaring `Equals(object)` or the operators yourself is error CS0111, and declaring only one of `Equals` and `GetHashCode` earns warning CS8851.

code

csharp · 29 lines
csharp
var a1 = new Address("Lyon", ["12 Rue X", "Apt 4"]);
var a2 = new Address("Lyon", ["12 Rue X", "Apt 4"]);
Console.WriteLine(a1 == a2);   // False: the two List<string> objects differ
Console.WriteLine(a1);         // Lines = System.Collections.Generic.List`1[System.String]

var f1 = new FixedAddress("Lyon", ["12 Rue X", "Apt 4"]);
var f2 = new FixedAddress("Lyon", ["12 Rue X", "Apt 4"]);
Console.WriteLine(f1 == f2);                               // True
Console.WriteLine(f1.GetHashCode() == f2.GetHashCode());   // True

public record Address(string City, List<string> Lines);

public record FixedAddress(string City, IReadOnlyList<string> Lines)
{
    public virtual bool Equals(FixedAddress? other) =>
        other is not null
        && EqualityContract == other.EqualityContract
        && City == other.City
        && Lines.SequenceEqual(other.Lines);

    public override int GetHashCode()
    {
        var hash = new HashCode();
        hash.Add(EqualityContract);
        hash.Add(City);
        foreach (var line in Lines) hash.Add(line);
        return hash.ToHashCode();
    }
}

go deeper

for a junior

Remember that a record compares each field with that field's own Equals, and that a List<T> is equal only to itself.

for a middle

Walk through the synthesized Equals: null check, EqualityContract, then the default comparer per field, and show the typed Equals plus GetHashCode pair that fixes the list.

for a senior

Spot the duplicate set entries and missed dictionary lookups this causes in review, and weigh element-wise equality against its cost on long lists and against mutable lists changing the hash.

for a principal

Set the team's rule for collection members in records used as keys or compared values: avoid them, or require hand-written equality with tests that pin it.

## How a record decides two instances are equal A record class gets a compiler-written `Equals(R? other)` method, where `R` is the record type, and every other equality member leads to it: the `Equals(object?)` override casts with `as R` and calls it, and the `==` operator calls it after a reference check. Its steps are fixed by the C# records specification: 1. Return `false` if `other` is `null`. 2. In a record that derives from `object`, compare `EqualityContract` on both sides, so the run-time record types must match. A derived record instead calls the base record's `Equals` first, which performs that check and compares the inherited fields. 3. For every **instance field declared in this record**, call `EqualityComparer<TField>.Default.Equals(thisField, otherField)`. Positional properties count, because each has a hidden backing field. The synthesized `GetHashCode()` combines `EqualityContract` with `EqualityComparer<TField>.Default.GetHashCode` of the same fields. The key phrase is **each field with its own equality**. The record does not look inside a field; it asks the field's type how to compare itself. ## Why a List<string> breaks it `EqualityComparer<T>.Default` uses `IEquatable<T>` when the type implements it, otherwise `object.Equals`. `List<T>` does neither in a content-aware way: it inherits `object.Equals`, which is **reference equality**. So for `record Address(string City, List<string> Lines)`, two instances built from two separate lists with the same lines compare unequal and almost certainly hash differently. A `HashSet<Address>` keeps both, `Distinct()` returns both, and a `Dictionary<Address, T>` lookup with a freshly built key misses. | Field type | What the default comparer does | Result for equal-looking data | |---|---|---| | `string` | compares characters (ordinal) | equal | | `int`, `decimal`, `DateOnly` | compares values | equal | | another record, such as `Money` | calls that record's synthesized `Equals` | equal, nested as deep as the records go | | `List<T>`, `T[]` | inherited reference equality | unequal unless it is the same instance | | `ImmutableArray<T>`, `ImmutableList<T>` | no element-by-element comparison either | unequal for separately built collections | The last row surprises people: an immutable collection is not a collection with structural equality. Immutability says the contents cannot change, not that two instances with the same contents are equal. The generated `ToString` shows the same blind spot: it prints the list as ``System.Collections.Generic.List`1[System.String]``, the type name, never the lines. ## The fix: your own Equals(Address?) and GetHashCode The compiler skips any synthesized member you declare with a matching signature, and the strongly typed `Equals` is one of the members you may declare. The snippet below declares both members; it keeps the `EqualityContract` check so derived records still never equal the base: ```csharp public record FixedAddress(string City, IReadOnlyList<string> Lines) { public virtual bool Equals(FixedAddress? other) => other is not null && EqualityContract == other.EqualityContract && City == other.City && Lines.SequenceEqual(other.Lines); public override int GetHashCode() { var hash = new HashCode(); hash.Add(EqualityContract); hash.Add(City); foreach (var line in Lines) hash.Add(line); return hash.ToHashCode(); } } ``` `Equals(object)`, `==` and `!=` are still generated and now reach your method, so every way of comparing agrees. ## Rules the compiler enforces - `public override bool Equals(object? obj)` cannot be declared: error **CS0111**, because the compiler always generates it. - `operator ==` and `operator !=` cannot be declared either: also CS0111. - In a record that is not `sealed`, your `Equals(Address?)` must be `virtual`; a non-virtual one is error **CS8872**. In a `sealed` record it may be non-virtual. - Declaring `Equals(Address?)` without `GetHashCode()` compiles but warns: **CS8851** `'Address' defines 'Equals' but not 'GetHashCode'`. Treat it as an error: a record whose `Equals` and `GetHashCode` disagree breaks every hash-based collection. ## Choosing between the fixes - **Hand-written element comparison** (above) is precise but costs a loop on every comparison and every hash, which matters for long lists used as keys. - **Keep collections out of value records** used for equality: store a fixed set of fields (`Line1`, `Line2`) or a single normalized string when the shape allows it. - **Accept reference equality knowingly** when the record is only a data carrier and nobody compares it; say so in a comment. - **Beware mutable lists in hashed records**: once `GetHashCode` hashes the elements, adding a line to the list changes the hash of a record already stored in a set or dictionary. ## What to say in an interview Say that record equality is per field, through `EqualityComparer<T>.Default`, and therefore only as deep as each field type's own `Equals`. Name the list as the field that falls back to reference equality, give the typed `Equals` plus `GetHashCode` pair as the repair, and mention CS0111 and CS8851 as the compiler's guard rails.

  • Does the same problem hit a C# record whose property is a string[] or an ImmutableArray<string>?
    Yes. Arrays inherit reference equality, and neither `ImmutableArray<T>` nor `ImmutableList<T>` compares elements, so two separately built collections with the same contents still make the records unequal. Immutability means the contents cannot change; it does not give the collection structural equality. Only a field type whose own `Equals` compares content, such as `string` or another record, keeps the record's value equality intact.
  • What does a property whose type is another record do to a C# record's equality?
    It nests. For `record OrderLine(Money Price, int Quantity)` the default comparer calls `Money`'s synthesized `Equals`, which compares `Amount` and `Currency`, so two lines with equal prices compare equal. The nesting continues through records of records and stops at the first member whose type has reference equality, such as a `List<T>` or an ordinary class.

  • Record equality compares collection properties element by element automatically.
  • Making the list property init-only makes it compare by value.
  • Override Equals(object) in the record to compare the list contents.
  • Custom record Equals can be written without touching GetHashCode.
  • Switching List<string> to ImmutableList<string> gives the record value equality.