Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Classes and Object-Oriented Concepts

Equals() and GetHashCode()

Reference for overriding Equals and GetHashCode in C#: the equality contract, IEquatable<T>, HashCode.Combine, == operators and the mutable-key bug.

Every .NET type inherits Equals(object?) and GetHashCode() from System.Object. For classes the default Equals compares references: two variables are equal only if they point to the same object. For structs the default compares fields by reflection, which is correct but slow. When you want your own notion of equality, such as "two Money values are equal if amount and currency match", you override both methods together.

Hash-based collections (Dictionary<TKey, TValue>, HashSet<T>) call GetHashCode() first to pick a bucket and Equals second to confirm a match. If the two disagree, items disappear from lookups. That is why the compiler warns when you override one without the other.

C#
public override bool Equals(object? obj) => obj is Money m && Equals(m);
public override int GetHashCode() => HashCode.Combine(Amount, Currency);

Try it

C# Value equality for a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# The mutable key bug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public virtual bool Equals(object? obj);
public virtual int GetHashCode();

// IEquatable<T>
bool Equals(T? other);

// static helpers
public static bool Equals(object? a, object? b);
public static bool ReferenceEquals(object? a, object? b);
Member Description
Equals(object?) Returns true if the objects are considered equal. The default for classes is reference equality.
GetHashCode() Returns an int that must be the same for equal objects.
IEquatable<T>.Equals(T?) Type-safe equality; avoids boxing for structs and is used by generic collections.
object.Equals(a, b) Static; handles null on either side, then calls a.Equals(b).
HashCode.Combine(...) Mixes up to eight values into one hash code.

Usage notes

  • The contract. Equality must be reflexive (x.Equals(x)), symmetric, transitive and consistent over time; it must never throw for null (return false). If a.Equals(b) then a.GetHashCode() == b.GetHashCode(). The reverse need not hold: different objects may share a hash code.
  • Hash codes are not stable across processes. string.GetHashCode() and HashCode.Combine use a random seed per run. Never store them or print them as identifiers.
  • Use immutable fields for the hash. If a field that feeds GetHashCode() changes while the object sits in a HashSet or a Dictionary key, the entry is stuck in the wrong bucket and lookups fail, as the second example shows.
  • Implement IEquatable<T> on structs. Without it, Equals(object) boxes the argument on every call.
  • Override == and != only for value-like types. If you do, keep them consistent with Equals. Records and record struct generate all of this for you; see Records and value equality.
  • Compare strings and floats deliberately. double.NaN.Equals(double.NaN) is true, but double.NaN == double.NaN is false.
  • Inheritance complicates equality. A Point and a ColorPoint cannot easily be both symmetric and value-based. Prefer sealed types or composition.
  • Collections accept a comparer. To change equality without changing the type, pass an IEqualityComparer<T> to the collection.