In C#, why is a Customer record never equal to a PremiumCustomer record with the same Id and Name, even through Customer-typed variables?
answer
- the run-time type takes part
- a protected Type-valued property
- typeof of each record
- derived Equals(Base?) is sealed
basics
~20 sEvery record's synthesized Equals compares EqualityContract, which returns typeof of the record's own type, and a derived record's sealed Equals(Customer?) re-dispatches through an as cast, so different run-time types never compare equal, whatever the variable type.
solid answer
~30 sThe root record's synthesized `Equals(Customer?)` checks `EqualityContract == other.EqualityContract` before it compares fields, and `EqualityContract` returns `typeof(Customer)` in `Customer` and `typeof(PremiumCustomer)` in the derived record. `PremiumCustomer` also gets `public sealed override bool Equals(Customer? other)`, which calls `Equals((object?)other)` and from there `Equals(other as PremiumCustomer)`; a plain `Customer` becomes `null`. So `regular == premium` and `premium.Equals(regular)` are both `false`, in both directions, even though both variables are typed `Customer` and `==` binds to `Customer`'s operator. `GetHashCode` mixes `EqualityContract` in too, so a `HashSet<Customer>` treats them as different elements. Overriding `EqualityContract` to return the base type compiles but makes equality asymmetric.
code
csharp · 16 linesCustomer regular = new Customer(7, "Ana");
Customer premium = new PremiumCustomer(7, "Ana", 10);
Console.WriteLine(regular == premium); // False: EqualityContract differs
Console.WriteLine(regular.Equals(premium)); // False
Console.WriteLine(premium.Equals(regular)); // False
var known = new HashSet<Customer> { regular };
Console.WriteLine(known.Contains(premium)); // False
var (id, name) = premium; // Customer.Deconstruct: two values
Console.WriteLine($"{id} {name}"); // 7 Ana
public record Customer(int Id, string Name);
public record PremiumCustomer(int Id, string Name, int DiscountPercent)
: Customer(Id, Name);go deeper
Remember the rule: two record instances are equal only when their run-time types match and their values are equal, so a derived record never equals its base.
Name EqualityContract, say it returns typeof of the record's own type, and show where the synthesized Equals compares it before the fields.
Trace both directions through the derived record's sealed Equals(Base?) override, explain why hashing agrees, and flag an EqualityContract override in review as an asymmetry bug.
Ask whether a tier such as premium belongs in a record subtype at all when the business treats both as the same customer; the generated equality says they are not.
## The members involved Record inheritance is legal only between records: a record cannot derive from a class other than `object`, and a class that tries to derive from a record fails with CS8865 (`Only records may inherit from records.`). For `record Customer(int Id, string Name)` and `record PremiumCustomer(int Id, string Name, int DiscountPercent) : Customer(Id, Name)` the compiler writes these equality members: | Member | In `Customer` | In `PremiumCustomer` | |---|---|---| | `EqualityContract` | `protected virtual Type`, returns `typeof(Customer)` | `protected override`, returns `typeof(PremiumCustomer)` | | `Equals(Customer?)` | `public virtual`; checks contract, then `Id`, `Name` | `public sealed override`; calls `Equals((object?)other)` | | `Equals(PremiumCustomer?)` | none | `public virtual`; calls `base.Equals((Customer?)other)`, then `DiscountPercent` | | `Equals(object?)` | `Equals(obj as Customer)` | `Equals(obj as PremiumCustomer)` | | `GetHashCode()` | combines the contract's hash, `Id`, `Name` | combines `base.GetHashCode()` and `DiscountPercent` | | `==`, `!=` | for `Customer?` operands | for `PremiumCustomer?` operands | **EqualityContract** is the property that carries the run-time type into the comparison. Because it is virtual, reading it on any instance gives that instance's actual record type. ## Tracing regular == premium Take `Customer regular = new Customer(7, "Ana");` and `Customer premium = new PremiumCustomer(7, "Ana", 10);`. 1. Both variables are typed `Customer`, so `==` binds to `Customer`'s operator. 2. The operator sees two different references and calls `regular.Equals(premium)`, the virtual `Equals(Customer?)`. 3. `regular` is a plain `Customer`, so `Customer`'s own `Equals(Customer?)` runs. 4. It compares `EqualityContract`: `typeof(Customer)` on the left, `typeof(PremiumCustomer)` on the right. They differ, so it returns `false` before looking at `Id` or `Name`. ## Tracing premium.Equals(regular) 1. The call is the virtual `Equals(Customer?)`, and `premium` is a `PremiumCustomer`, so its `sealed override Equals(Customer?)` runs. 2. That override calls `Equals((object?)regular)`, which is `PremiumCustomer`'s `Equals(object?)`. 3. That casts with `regular as PremiumCustomer`, which is `null` for a plain `Customer`. 4. `Equals(PremiumCustomer? other)` returns `false` for `null`. Both directions give `false`, so equality stays **symmetric**, which is what hash-based collections and `Distinct` rely on. ## Why the records design works this way Equality across a class hierarchy has a well-known trap: if a derived type adds a field, comparing a base instance with a derived one either ignores that field, so two derived instances that differ only in the new field both equal the same base instance while being unequal to each other, or gives different answers depending on which side you call. The C# records design picks one rule and generates it everywhere: - **Same run-time type, then equal fields.** No subtype ever equals its base, so the extra fields can never be ignored. - **Every path agrees.** `Equals(object?)`, `Equals(Customer?)`, `Equals(PremiumCustomer?)`, `==` and `GetHashCode` all reach the same contract check. - **No hand-written override can undo it by accident**, because the members that would break it, the derived `Equals(Base?)` and the operators, cannot be declared. ## What else follows the run-time type, and what does not - **GetHashCode** starts from the root's hash of `EqualityContract`, so `new HashSet<Customer> { regular }.Contains(premium)` is `false` and a dictionary keeps both as separate keys. - **ToString** prints the run-time type's name and all members, base first. - A **`with` expression** through a `Customer` variable copies the run-time type; that rule belongs with nondestructive mutation. - **Deconstruct does not follow it.** `Deconstruct` is an ordinary, non-virtual method chosen by the variable's compile-time type, so `var (id, name) = premium;` calls `Customer`'s two-value `Deconstruct` and yields `7` and `Ana`. ## Ways to break it, and why not to - **Overriding `EqualityContract`** in `PremiumCustomer` to return `typeof(Customer)` compiles, because the property may be declared explicitly. The result is asymmetric: `regular.Equals(premium)` runs `Customer`'s method, sees matching contracts and equal fields, and returns `true`; `premium.Equals(regular)` still goes through the `as PremiumCustomer` cast and returns `false`. - **Declaring `Equals(Customer?)` in the derived record** is not allowed: the compiler always generates it as a sealed override, and a hand-written one is error **CS0111**. - **Comparing only base members** across the hierarchy is something the generated members are designed to prevent. If the domain needs "same customer regardless of tier", compare `Id` explicitly at the call site, or keep the tier as data instead of as a subtype. - **Sealing leaf records** (`sealed record PremiumCustomer`) does not change equality, but it makes `EqualityContract` effectively sealed, so no later subtype can override it. ## What to say in an interview Say that record equality includes the run-time type, name `EqualityContract` as the mechanism, and trace one direction through the derived record's sealed `Equals(Base?)` override. Then mention the two traps: `Deconstruct` binds to the static type, and overriding `EqualityContract` breaks symmetry.
- In C#, what happens if a derived record PremiumCustomer overrides EqualityContract to return typeof(Customer)?It compiles, and equality turns asymmetric. `regular.Equals(premium)` runs `Customer`'s `Equals`, finds matching contracts and equal `Id` and `Name`, and returns true. `premium.Equals(regular)` goes through `PremiumCustomer`'s sealed `Equals(Customer?)`, casts the plain `Customer` with `as PremiumCustomer`, gets `null` and returns false. Hash sets and `Distinct` then behave differently depending on argument order.
- In C#, what does `var (id, name) = c;` give when a Customer variable c holds a PremiumCustomer?`7` and `Ana`. Deconstruction picks a `Deconstruct` method by the variable's compile-time type, so `Customer`'s two-parameter `Deconstruct` runs. The synthesized `Deconstruct` is not virtual, so the discount is never returned unless you cast to `PremiumCustomer` first and deconstruct into three variables.
- Can a derived C# record declare its own Equals(Customer? other) to compare only the base members?No. The compiler always writes that method as `public sealed override bool Equals(Customer? other)`, and declaring it is error CS0111. The generated override forwards to `Equals(object)`, which casts with `as PremiumCustomer`, so from the derived side a plain `Customer` always arrives as `null`.
- Equality uses the variable's declared type, so two Customer variables compare only Customer's members.
- A derived record equals its base record when the base properties match.
- EqualityContract is generated by reflection and cannot be declared in source.
- Deconstruct through a base-typed variable returns the derived record's extra values.
- Overriding EqualityContract to the base type gives symmetric base-to-derived equality.