skip to content

In C#, why does an Equals override written with `obj is LineItem` break symmetry once GiftLineItem derives from it, and what does a GetType() check change?

level: seniorimportance: should knowfreq 40%

answer

  1. is accepts every subclass
  2. a.Equals(b) versus b.Equals(a)
  3. set results depend on order
  4. compare run-time types

basics

~20 s

An is LineItem test accepts any subclass, so a plain item can equal a gift item while the gift's own Equals rejects the plain one. Comparing GetType() in the base Equals makes objects of different run-time types unequal, restoring symmetry.

solid answer

~40 s

With `obj is LineItem other`, the base `Equals` treats a `GiftLineItem` as a `LineItem` and compares only `Sku` and `Quantity`, so `plain.Equals(gift)` is `true`. The derived override tests `obj is GiftLineItem` and also compares `Message`, so `gift.Equals(plain)` is `false`. That breaks **symmetry**, one of the rules `Equals` must obey, and collections then give order-dependent answers: a `HashSet<LineItem>` can keep one or both items depending on which was added first. The fix is a `GetType() == other.GetType()` guard in the base comparison, ideally in a `virtual Equals(LineItem? other)` that subclasses extend with `base.Equals`, plus `GetType()` in the hash. Sealing the class makes the plain `is` test safe again.

code

csharp · 24 lines
csharp
var plain = new LineItem("SKU-42", 2);
var gift = new GiftLineItem("SKU-42", 2, "Happy birthday");

Console.WriteLine(plain.Equals(gift)); // True:  `is LineItem` accepts the subclass
Console.WriteLine(gift.Equals(plain)); // False: `is GiftLineItem` rejects the base
Console.WriteLine(new HashSet<LineItem> { plain, gift }.Count); // 1: the gift line vanished
Console.WriteLine(new HashSet<LineItem> { gift, plain }.Count); // 2: same items, other order

class LineItem(string sku, int quantity)
{
    public string Sku { get; } = sku;
    public int Quantity { get; } = quantity;
    public override bool Equals(object? obj) =>
        obj is LineItem other && Sku == other.Sku && Quantity == other.Quantity;
    public override int GetHashCode() => HashCode.Combine(Sku, Quantity);
}

class GiftLineItem(string sku, int quantity, string message) : LineItem(sku, quantity)
{
    public string Message { get; } = message;
    public override bool Equals(object? obj) =>
        obj is GiftLineItem other && base.Equals(other) && Message == other.Message;
    public override int GetHashCode() => base.GetHashCode(); // legal: equal gifts share it
}

go deeper

for a junior

Recall that Equals must be symmetric: if a equals b, then b must equal a. Know that an is check in a base class also matches every subclass.

for a middle

Trace both calls between a base and a derived object with is checks, show which rule breaks, and write the GetType() guard version.

for a senior

Explain how the asymmetry surfaces as order-dependent HashSet or Distinct results in production, and choose between sealing, a GetType() guard with a virtual typed Equals, or a record.

for a principal

Set the default for a codebase: value-like classes are sealed or records, and any hand-written equality in a hierarchy follows one reviewed pattern with a virtual typed Equals and a type guard.

## The equivalence rules Equals must follow `Equals` is expected to define an **equivalence relation**. For non-null `x`, `y` and `z`: - **Reflexive**: `x.Equals(x)` is `true`. - **Symmetric**: `x.Equals(y)` and `y.Equals(x)` return the same value. - **Transitive**: if `x.Equals(y)` and `y.Equals(z)`, then `x.Equals(z)`. - **Consistent**: repeated calls return the same value while neither object changes. - `x.Equals(null)` is `false` and does not throw. `HashSet<T>`, `Dictionary<TKey,TValue>`, `List<T>.Contains` and LINQ's `Distinct` all assume these rules. They call `Equals` with the two objects in whatever order their algorithm happens to use, so an asymmetric `Equals` makes the result depend on internal details. ## How `is` breaks symmetry The type pattern `obj is LineItem other` succeeds for a `LineItem` **and every type derived from it**. Consider: 1. `LineItem.Equals` accepts any `LineItem` and compares `Sku` and `Quantity`. 2. `GiftLineItem : LineItem` adds `Message`, and its override requires `obj is GiftLineItem` and compares `Message` as well. 3. `plain.Equals(gift)` runs the base override: the gift is a `LineItem`, the shared fields match, so it returns `true`. 4. `gift.Equals(plain)` runs the derived override: the plain item is not a `GiftLineItem`, so it returns `false`. Symmetry is broken. Transitivity is not affected by this particular pair of overrides, which is why the failure is easy to miss in a unit test that only compares in one direction. ## What it does to a collection In the first snippet, `GiftLineItem.GetHashCode` returns the base hash, which is legal because equal gift items share it. Both objects then hash alike, and the set has to ask `Equals`. On .NET 10, `new HashSet<LineItem> { plain, gift }.Count` printed 1 and `new HashSet<LineItem> { gift, plain }.Count` printed 2: which override runs depends on which item is already stored, and the two overrides disagree. A cart that deduplicates line items would silently drop the gift message for one insertion order and keep it for the other. ## The GetType() fix The pattern recommended in Microsoft's equality guidance for unsealed hierarchies has three parts: - **A `virtual` typed comparison**: `public virtual bool Equals(LineItem? other)`, so each subclass can extend it. - **A run-time type guard** in the base: `other is not null && GetType() == other.GetType() && ...`. Objects of different run-time types are never equal, whichever side the call starts from. - **The hash includes the type** (`HashCode.Combine(GetType(), Sku, Quantity)`) and each subclass adds its own fields. Equal objects still share a hash, and a plain item and a gift item with the same shared fields usually stop colliding. The derived class overrides `Equals(LineItem? other)`, calls `base.Equals(other)` (which enforces the type guard and the shared fields), and then compares `Message`. `Equals(object)` is overridden once in the base and forwards to the typed method. | Approach | plain vs gift | Subclass adds fields safely | Note | |---|---|---|---| | `is` check, unsealed class | asymmetric | no | order-dependent collections | | `GetType()` guard, virtual typed `Equals` | both `false` | yes | a subclass never equals its base | | `is` check, `sealed` class | not applicable | no subclasses | simplest when inheritance is not needed | ## Testing equality in both directions Unit tests for a hierarchy with value equality should cover the cases that one-directional tests miss: - Assert `a.Equals(b) == b.Equals(a)` for every pair in a small matrix that mixes base and derived instances. - Add the same items to a `HashSet<T>` in both orders and compare the counts. - Assert that `GetHashCode` values are equal whenever `Equals` returns `true`. ## Choosing between them - **Seal value-like classes** unless there is a real reason to derive. A sealed class has no subclasses, so the simple `is` test is already symmetric. - **Use `GetType()`** when a hierarchy must have value equality. The trade-off is deliberate: a `GiftLineItem` can never equal a `LineItem`, even if the shared fields match. - **Records** solve the same problem automatically through a generated `EqualityContract` property that compares run-time types; that generated code is covered with records. - **A non-virtual `Equals(LineItem? other)`** from `IEquatable<LineItem>` dispatches on the declared type, so a call through a `LineItem` variable that holds a gift ignores `Message`. Making it `virtual` closes that hole.

  • Why is `GetType()` in the base `GetHashCode` not strictly required for correctness?
    The contract only demands that equal objects share a hash. With the `GetType()` guard, objects of different run-time types are never equal, so their hashes may collide freely. Including the type simply spreads a plain item and a gift item with the same shared fields into different buckets, which avoids needless `Equals` calls.
  • What goes wrong if the typed `Equals(LineItem? other)` from `IEquatable<LineItem>` is not virtual?
    A call through a variable declared as `LineItem` binds to the base method even when both objects are gift items, so `Message` is never compared and two gifts with different messages look equal. Making the method `virtual` and overriding it in `GiftLineItem` restores dispatch on the run-time type.

  • Using is in Equals is always safe because the cast cannot fail
  • Symmetry problems only matter if someone calls Equals in both directions by hand
  • A HashSet result cannot depend on the order items were added
  • The GetType() check lets a subclass equal its base when shared fields match
  • Overriding Equals in the subclass alone fixes the asymmetry