Overriding GetHashCode
Keep equality and hashing consistent.
Why GetHashCode Matters
Hash-based collections like Dictionary and HashSet use GetHashCode to bucket items. If you override Equals but not GetHashCode, these collections can fail to find equal items.
The Golden Rule
The contract is simple: if two objects are equal, they must return the same hash code. The reverse is not required; different objects may share a hash code (a collision).
using System;
public struct Point
{
public int X, Y;
public Point(int x, int y) { X = x; Y = y; }
public override bool Equals(object obj) => obj is Point p && p.X == X && p.Y == Y;
public override int GetHashCode() => HashCode.Combine(X, Y);
}
public class Program
{
public static void Main()
{
var a = new Point(1, 2);
var b = new Point(1, 2);
Console.WriteLine(a.Equals(b));
Console.WriteLine(a.GetHashCode() == b.GetHashCode());
}
}All lessons in this course
- Implementing IEquatable
- Overriding GetHashCode
- Implementing IComparable
- IComparer for Custom Sorting