2026-06-09 / C# / .NET Core
C# Equals, GetHashCode, and Hash Collection Semantics
Why custom equality must handle both Equals and GetHashCode, and how hash-based collections use them.
C#.NET
C# Equals, GetHashCode, and Hash Collection Semantics
If an object is used in Dictionary or HashSet, overriding only Equals is not enough. GetHashCode must match the equality semantics.
Hash collections usually locate a bucket by hash code first, then confirm equality. If two logically equal objects produce different hash codes, lookup, removal, or de-duplication may fail.
Best Practices
- Implement
EqualsandGetHashCodetogether when defining value equality. - Prefer immutable objects as hash keys.
- Do not generate hash codes from random or mutable state.
- Consider records when they fit value-object semantics.