🔧 C#: Fix a Record Struct Losing Equality After Adding a Field
A record struct’s compiler-generated Equals and GetHashCode compare every field the record declares, generated fresh at compile time from whatever the type’s member list looks like right then – there’s no runtime reflection involved, so adding a new field to the record regenerates both methods automatically and correctly. The actual trap is a record struct that implements IEquatable<T> or overrides Equals manually for a special case (ignoring a cache field, say) – adding a new field later doesn’t touch that hand-written method at all, so the new field silently never participates in equality while every auto-generated comparison elsewhere in the codebase still works, hiding the gap.
🔎 The Problem
public readonly record struct Money
{
public decimal Amount { get; init; }
public string Currency { get; init; }
public bool Equals(Money other) =>
Amount == other.Amount && Currency == other.Currency;
// hand-written override, correct for 2 fields
}
// Later: a RoundingMode field is added to the record
// public RoundingMode RoundingMode { get; init; }
// The hand-written Equals above is NEVER updated - two Money values
// with different RoundingMode now compare as equal silently
✅ The Fix
- Delete the hand-written Equals/GetHashCode entirely unless you have a specific, documented reason to exclude a field from equality, and let the compiler regenerate both from the full current field list every time the record changes.
- If a field genuinely should be excluded from equality (a cached, derived value, for instance), say so explicitly in a comment right next to the custom Equals implementation, so the next person adding a field sees the warning before they assume equality is still automatic.
- Add a unit test that constructs two instances differing only in the newest field and asserts they are NOT equal, specifically to catch exactly this class of silently-stale custom equality the next time a field gets added.
🚨 Why This Is Dangerous
Silently broken equality doesn’t throw anywhere – it just makes two genuinely different values compare as equal, which can corrupt a HashSet, a Dictionary key, or a deduplication step with no exception to point at and no obvious place to start looking.
The compiler only regenerates the equality it’s responsible for – the moment you write your own Equals by hand, every new field is on you to remember.



