C# › Equality: Equals, GetHashCode & IEquatable

How do you correctly override Equals() and GetHashCode() together on a class, and why must they always be overridden as a pair?

Intermediate

Answer

.NET's contract requires that if two objects are Equal() (return true), they MUST also return the SAME GetHashCode() value — hash-based collections like Dictionary and HashSet rely on this to correctly bucket and find equal objects; overriding only one breaks that contract and causes subtle collection bugs.
public class Point {
  public int X, Y;
  public override bool Equals(object? obj) =>
    obj is Point other && X == other.X && Y == other.Y;
  public override int GetHashCode() => HashCode.Combine(X, Y);
}
Real-world example Correctly making a custom class usable as a Dictionary key or HashSet element based on its logical, value-based identity.

Common follow-ups: What specifically goes wrong in a Dictionary or HashSet if you override Equals() but forget GetHashCode()?