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.
public override bool Equals(object? obj) => obj is Money m && Equals(m); public override int GetHashCode() => HashCode.Combine(Amount, Currency);
Try it
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.
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
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 fornull(returnfalse). Ifa.Equals(b)thena.GetHashCode() == b.GetHashCode(). The reverse need not hold: different objects may share a hash code. - Hash codes are not stable across processes.
string.GetHashCode()andHashCode.Combineuse 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 aHashSetor aDictionarykey, 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 withEquals. Records andrecord structgenerate all of this for you; see Records and value equality. - Compare strings and floats deliberately.
double.NaN.Equals(double.NaN)istrue, butdouble.NaN == double.NaNisfalse. - Inheritance complicates equality. A
Pointand aColorPointcannot 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.