Equality and hash contracts
Equality and hash contracts
Equality answers whether two values should be treated as equivalent for a particular operation. Identity asks whether two references designate the same object. object.ReferenceEquals tests identity; Equals and == follow their applicable type contracts and need not agree for every type. A regular class without custom equality uses reference equality; records supply value-oriented equality.
A hash code helps a hash-based collection narrow the search for an equal key. With a given equality comparer, equal keys must have equal hashes. Unequal keys may share a hash (a collision). A dictionary uses its comparer to find a key, not only the hash. Do not persist hash codes as unique IDs or expect their values to remain stable across processes.
using System;var a = new Ticket(18);var b = new Ticket(18);Console.WriteLine(a == b);Console.WriteLine(a.Equals(b));Console.WriteLine(object.ReferenceEquals(a, b));Console.WriteLine(a.GetHashCode() == b.GetHashCode());record Ticket(int Number);Two record objects represent equal values but are distinct instances. Equal hash codes are required for these equal records; their actual numeric hash is deliberately not printed.
Expected output (reasoned, not executed):
TrueTrueFalseTrueBuild on the first example
using System;using System.Collections.Generic;var counts = new Dictionary<ShelfKey, int>();counts.Add(new ShelfKey(2, 4), 12);Console.WriteLine(counts.TryGetValue(new ShelfKey(2, 4), out int count));Console.WriteLine(count);Console.WriteLine(counts.ContainsKey(new ShelfKey(2, 5)));readonly record struct ShelfKey(int Aisle, int Slot);Dictionary maps keys to values. The default comparer for this key type uses the generated equality; a newly constructed equivalent key finds the original entry. TryGetValue reports whether a match exists.
Expected output (reasoned, not executed):
True12FalseApply the idea to another case
using System;var a = new BatchId(7);var b = new BatchId(7);Console.WriteLine(a.Equals(b));Console.WriteLine(a.GetHashCode() == b.GetHashCode());Console.WriteLine(a == b);sealed class BatchId{ public int Number { get; } public BatchId(int number) => Number = number; public override bool Equals(object? obj) => obj is BatchId other && Number == other.Number; public override int GetHashCode() => Number.GetHashCode();}The type pattern checks whether obj is a BatchId and binds other; this is a preview of the next chapter. The sealed class overrides Equals and GetHashCode consistently but does not overload ==, so == still compares references. For a production value class consider aligning operators and implementing typed IEquatable<T> too.
Expected output (reasoned, not executed):
TrueTrueFalseCommon mistakes and design choices
Never change an equality-relevant key property while the object is stored in a dictionary. The lookup can search using a different hash or equality relation than insertion. Use immutable key values, including their equality-relevant members, or remove and reinsert intentionally before changing them. Do not assert unequal values have unequal hashes. A custom equality relation should be reflexive, symmetric and transitive for its intended domain; its hash implementation must agree with it.
Practice
Use a readonly record struct SlotKey(string Room, int Slot) as a dictionary key. Insert ("A", 2) with value 6. Look up a fresh equivalent key and then ("A", 3). Explain why equal hashes alone cannot prove equality.
Use the manual practice task and knowledge check to verify your understanding. All examples target C# 14 / .NET 10; execution and ByteMind renderer support remain unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Equality and hash contracts — knowledge check
Apply the lesson concepts to the following scenarios.
What must be true of equal keys under the same comparer?
Do matching hash codes prove two keys are equal?
Why use immutable equality-relevant fields for a dictionary key?
Why does a == b print False for BatchId?
What is the value of ReferenceEquals(a,b) for two separately constructed equal Ticket records?