Equality & hashing (value vs reference)
Understand reference vs value equality, override Equals/GetHashCode correctly, implement IEquatable , and use custom comparers with sets/dictionaries.
Equality basics
Goal: Make equality work as you expect.
- Reference vs value equality
- Equals + GetHashCode contract
- IEquatable<T> for speed
- Custom comparers when you cannot modify the type
Reference equality pitfall
Classes default to reference equality. Two separate objects with same data are not equal unless you implement value equality.
using System;
using System.Collections.Generic;
public sealed class Point // no overrides
{
public int X;
public int Y;
public Point(int x, int y){ X = x; Y = y; }
}
public class Program
{
public static void Main(string[] args)
{
Point a = new Point(1, 2);
Point b = new Point(1, 2);
Console.WriteLine("a == b ? " + (a == b)); // reference equality: False
Console.WriteLine("a.Equals(b) ? " + a.Equals(b)); // False
HashSet<Point> set = new HashSet<Point>();
set.Add(a);
Console.WriteLine("Contains b? " + set.Contains(b)); // False (unexpected)
}
}
All lessons in this course
- HashSet , SortedSet , Queue , Stack
- ConcurrentDictionary , immutable collections
- Equality & hashing (value vs reference)