Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 12

    Module 1 · Equality, comparers and reliable keys · Lesson 1 of 12

    Equality and Hash-Code Contracts for Immutable C# Value Keys

    Lesson video

    When should two prices count as one?

    Say a shop's list contains USD 19.99 twice and USD 20.00 once. If you're counting distinct prices, you want two entries. If the first price were EUR 19.99 instead, you'd keep it separate: the amount matches, but the currency doesn't. Equality is the rule that decides whether two values count as the same. In this lesson, two Money values are equal when both their amount and their currency match.

    A HashSet<T> stores one entry per value under its equality rule. A comparer supplies two operations: GetHashCode gives a number the set uses to choose a group of candidates (a bucket), and Equals tells the set whether a candidate really matches. Equal values must have the same hash under the same comparer. Different values are allowed to get the same hash. That's a collision, not proof that they're duplicates.

    First run the complete Money example and look for the two entries. Then reuse the lesson's constant-hash example to see exactly why the set calls both methods.

    Run and inspect the complete example

    Run this example

    Use the .NET 10 SDK. In a new empty folder, save the project below as Example.csproj and the listing as Program.cs. Run dotnet run --project Example.csproj.

    XML
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net10.0</TargetFramework>
        <ImplicitUsings>disable</ImplicitUsings>
        <Nullable>enable</Nullable>
      </PropertyGroup>
    </Project>

    Immutable value key with equality, hash-code checks, and collision awareness

    Program.cs

    C#
    using System;
    using System.Collections.Generic;
    
    public readonly record struct Money(string Currency, decimal Amount)
    {
        public override string ToString() => $"{Currency} {Amount:0.00}";
    }
    
    public static class Program
    {
        public static void Main()
        {
            var a = new Money("USD", 19.99m);
            var b = new Money("USD", 19.99m);
            var c = new Money("USD", 20.00m);
    
            Console.WriteLine($"a.Equals(b): {a.Equals(b)}");
            Console.WriteLine($"a hash == b hash: {a.GetHashCode() == b.GetHashCode()}");
            Console.WriteLine($"a.Equals(c): {a.Equals(c)}");
    
            Console.WriteLine($"a hash == c hash: {a.GetHashCode() == c.GetHashCode()}");
            Console.WriteLine($"a hash == c hash means equal: {a.GetHashCode() == c.GetHashCode() && a.Equals(c)}");
            Console.WriteLine($"a hash == c hash is just a collision check: {a.GetHashCode() == c.GetHashCode()}");
    
            var set = new HashSet<Money> { a, b, c };
            Console.WriteLine($"HashSet count: {set.Count}");
            Console.WriteLine($"Contains USD 19.99: {set.Contains(new Money("USD", 19.99m))}");
            Console.WriteLine($"Contains USD 20.00: {set.Contains(new Money("USD", 20.00m))}");
    
            Console.WriteLine(a == b ? "Equality operator agrees" : "Equality operator disagrees");
        }
    }

    Expected output

    One permitted output is shown below. Both collision-check lines may instead be True, but they must agree. Equal hashes never override the False equality result for a and c.

    Text
    a.Equals(b): True
    a hash == b hash: True
    a.Equals(c): False
    a hash == c hash: False
    a hash == c hash means equal: False
    a hash == c hash is just a collision check: False
    HashSet count: 2
    Contains USD 19.99: True
    Contains USD 20.00: True
    Equality operator agrees

    The equality and hash contracts

    For a value object, equality should be based on the logical data the type represents, not on object identity. For an immutable Money value, two instances with the same currency and amount should compare equal even when constructed separately. The record struct below is a value type; reference identity is not its equality model.

    In C#, the contract is simple:

    1. If a.Equals(b) is true, then a.GetHashCode() and b.GetHashCode() must return the same value.
    2. If a.GetHashCode() is the same as b.GetHashCode(), that does not prove a.Equals(b). Under one consistent, contract-correct comparer in the same execution, different hash codes rule out equality: this is the contrapositive of rule 1. In contrast, different values can have the same hash code, so matching hashes require an equality check. Do not compare hash codes from different comparers or processes as stable identities.
    3. Equals should be reflexive, symmetric, transitive, and consistent.
    4. Hashing must not distinguish values that equality treats as equal. Combining equality-relevant fields is the usual design; leaving one out can increase collisions without necessarily violating the contract.

    You often see this implemented manually for classes and structs, but modern C# also gives records built-in value equality. For interview purposes, you should still understand the manual implementation because it shows the underlying contract clearly.

    A reliable immutable key keeps its equality-relevant state stable after construction. That prevents the value from changing after it has been inserted into a hash-based collection. If the logical value cannot change, the hash code cannot drift out from under the collection.

    Failure modes

    A few common mistakes come up repeatedly in interviews and production code:

    • Overriding Equals but not GetHashCode.
    • Using mutable fields in equality and then changing them after insertion into a HashSet or Dictionary.
    • Assuming same hash code means equal object.
    • Accidentally comparing reference identity for a value object.
    • Mixing comparer policy with type semantics: the type defines its own equality, but the collection may accept an external comparer that changes lookup behavior.

    Another subtle point: RuntimeHelpers.GetHashCode is about object identity-oriented hashing, not logical value equality. That makes it different from an overridden GetHashCode on your type.

    Explain the observed collection results

    Answer against the complete fixture, then compare with the responses.

    1. Why must equal objects have equal hash codes?
    2. Why are collisions allowed?
    3. What if equality says two keys are equal but their hashes differ?
    4. Why is immutability useful for hash keys?
    5. How do records simplify this example?
    6. How does collection policy differ from the type's own equality?

    Hint: Use the two USD 19.99 values as the equal pair and USD 20.00 as the unequal value.

    Worked responses

    1. Here, a and b both represent USD 19.99. Searching with either must lead to the same candidate entries; the set must treat the second as a duplicate.
    2. Imagine a and c receive the same hash. Their amounts still differ, so the equality check keeps both values. The set count remains 2.
    3. A lookup can search the wrong candidate group and miss an equal entry. In this fixture that would undermine the promise that another USD 19.99 finds the stored value.
    4. The inserted Money value cannot later change from USD 19.99 into USD 20.00. Its key identity stays aligned with the value originally stored.
    5. The listing declares no manual equality methods. The generated equality makes a.Equals(b) and a == b agree for these currency-and-amount values.
    6. This set uses its default policy for Money. In the next lesson, two string collections deliberately use different policies and produce different duplicate counts for the same inputs.

    The Equals / GetHashCode contract

    Equal values
    Must return the same hash code Two USD 19.99 values hash equally
    Same hash code
    Does not prove equality; it can be a collision USD 19.99 and USD 20.00 may share a hash
    Different hash codes
    Rule out equality under one consistent comparer Lookup can skip that candidate
    Stored keys
    Keep equality-relevant state stable while stored A readonly record struct key

    Two different Money values return the same hash code. What does a HashSet<Money> do when you add both?

    A Rejects the second value as a duplicate
    B Keeps both, because equality still decides the match
    C Throws an exception
    D Replaces the first value
    Show answer

    Correct answer: B

    A collision is allowed. The set calls Equals within the candidate group, and the values are not equal, so the count is 2.

    Code walkthrough

    The executable example compares three Money values. The first two are logically identical, so Equals returns true and their hash codes match. The third differs in amount, so Equals returns false.

    The program then inserts all three values into a HashSet<Money>. The set count stays at 2, because the duplicate logical value is not added twice. Finally, the program reports whether the third value collided with the first one by comparing hash codes. If they match, that is a collision, but not equality.

    That is the key interview idea: equal values must hash equally, but equal hashes do not prove equality.

    Quick reference: answer with evidence

    • State the equality rule before discussing a hash. In the existing Money example, currency and amount identify the value.
    • For a and b, the equality result and hash agreement are guaranteed. For a and c, matching hashes would be a collision, not a duplicate.
    • Explain the set count as two logical values. Do not base the answer on the numeric hashes printed by one machine.
    • Keep the key's equality-relevant state stable while it is stored. The example uses a readonly record struct containing a string and a decimal.
    • A collection can receive a different equality policy. Always identify which comparer a question uses before predicting a count.

    Make a collision predictable

    The existing program correctly permits either outcome for the unequal values' hash comparison. For a repeatable follow-up, keep Money unchanged and put this comparer alongside it:

    C#
    public sealed class CollisionComparer : IEqualityComparer<Money>
    {
        public bool Equals(Money x, Money y) => x.Equals(y);
        public int GetHashCode(Money value) => 0;
    }

    Inside Main, try:

    C#
    var demo = new HashSet<Money>(new CollisionComparer());
    Console.WriteLine(demo.Add(new Money("USD", 7m)));
    Console.WriteLine(demo.Add(new Money("USD", 9m)));
    Console.WriteLine(demo.Add(new Money("USD", 7m)));
    Console.WriteLine(demo.Count);

    Expected output:

    Text
    True
    True
    False
    2

    All three candidates receive hash 0. The second amount still earns a new entry; the repeated first amount does not. This comparer is a teaching fixture with deliberately poor distribution, not a production recommendation.

    Here is the call order for this example on .NET 10.0.15. The table traces the implementation; the code above prints only the results and count.

    CallWhat the comparer checksResult
    Add USD 7Hash USD 7. The bucket is empty, so no equality check.True
    Add USD 9Hash USD 9. Compare the existing USD 7 with USD 9: not equal.True
    Add USD 7 againHash USD 7. Compare the existing USD 9 first: not equal. Compare the existing USD 7 next: equal.False

    Count is still 2. The exact order of candidates within a bucket is not part of the HashSet contract. To see the calls yourself, add a Console.WriteLine at the start of each comparer method that prints its inputs, then run the demo again.

    An adjusted copy does not replace the stored value

    With the lesson's Money type, start with var original = new Money("USD", 7m);. Then var adjusted = original with { Amount = 9m }; creates an adjusted value while original stays USD 7. A set containing only original still finds that value and does not find adjusted until it is added. This copy-and-change expression does not mutate the key stored in the set.

    Optional challenge: separate type equality from collection policy

    Suppose a second comparer groups Money values by currency only. In that collection, USD 7 and USD 9 would share one group, while new Money("USD", 7m) == new Money("USD", 9m) would remain false. A custom comparer does not rewrite the record's generated operator.

    Source for the collection contract: Microsoft: IEqualityComparer.GetHashCode. The examples and reasoning above are original applications to this lesson's Money model.

    Optional video

    Watch Dev Leader: Beginner’s Guide to C# Record Equality (14:37). This free external walkthrough uses record classes, including a collection-member caveat. Return to this lesson for record structs and the precise hash-key contract.

    Practice

    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·