Skip to content

Equality and Hash Codes

The Course
•
25 min study

HashSet, Dictionary, Distinct, GroupBy and == all depend on your type's idea of "equal". Records generate a sensible answer. Knowing what they generate, and how to write it yourself, helps you avoid some bugs that are hard to find.

Reference or value

Classes compare by reference by default: two objects with the same contents aren't equal. Records and structs compare by value. Predict these.

What does equal mean here? C#
Console.WriteLine(new PersonClass("Ana").Equals(new PersonClass("Ana")));
Console.WriteLine(new PersonRecord("Ana").Equals(new PersonRecord("Ana")));
Console.WriteLine(new PersonStruct("Ana").Equals(new PersonStruct("Ana")));

class PersonClass(string name)
{
    public string Name { get; } = name;
}

record PersonRecord(string Name);

struct PersonStruct(string name)
{
    public string Name { get; } = name;
}
Check your prediction
Text
False
True
True

A plain struct's default Equals works, but uses reflection on many types and boxes its argument, so it's slow. Don't rely on it in hot code.

The contract

A hash table first compares hash codes, then calls Equals. So the one rule that can't be broken is: if two objects are equal, their hash codes must be equal. Break it, and a HashSet can't find what's in it. Here, Equals was overridden but GetHashCode wasn't.

Equal, yet not found C#
#nullable enable

var good = new HashSet<Good> { new Good(1) };
Console.WriteLine(good.Contains(new Good(1)));

var bad = new HashSet<Bad> { new Bad(1) };
Console.WriteLine(new Bad(1).Equals(new Bad(1)));
Console.WriteLine(bad.Contains(new Bad(1)));

record Good(int Id);

#pragma warning disable CS0659
class Bad(int id)
{
    public int Id { get; } = id;

    public override bool Equals(object? other) => other is Bad bad && bad.Id == Id;
}
Check your prediction
Text
True
True
False

The compiler warns about exactly this mistake with CS0659, and the #pragma line switches that warning off so that you can see the failure. The reverse needn't hold: unequal values may share a hash code, and that only costs a little speed.

Doing it properly

For a type that needs custom equality, implement IEquatable<T>, override Equals(object) and GetHashCode, and provide == and !=. HashCode.Combine does the mixing. This example treats tags that differ only in case as equal. The two sides must agree: if Equals ignores case, then so must the hash code.

Case-insensitive equality C#
#nullable enable

var tags = new HashSet<Tag> { new("Sale"), new("sale"), new("New") };
Console.WriteLine(tags.Count);
Console.WriteLine(new Tag("SALE") == new Tag("sale"));
Console.WriteLine(tags.Contains(new Tag("NEW")));
Tag? missing = null;
Console.WriteLine(missing == new Tag("sale"));
Console.WriteLine(missing == null);

sealed class Tag(string name) : IEquatable<Tag>
{
    public string Name { get; } = name;

    public bool Equals(Tag? other) => other is not null && string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase);

    public override bool Equals(object? other) => Equals(other as Tag);

    public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Name);

    public static bool operator ==(Tag? left, Tag? right) => left is null ? right is null : left.Equals(right);

    public static bool operator !=(Tag? left, Tag? right) => !(left == right);
}
Check your prediction
Text
2
True
True
False
True

Two details matter. The == operator checks left is null first: writing left.Equals(right) alone would throw NullReferenceException for missing == tag, and x == null is a comparison people write all the time. And Tag is sealed. If a ColoredTag could derive from it, tag.Equals(coloredTag) could say true while coloredTag.Equals(tag) said false, and equality must give the same answer both ways round.

That's a lot of code, which is why a record is usually better. You can also give a record your own Equals, or leave a type's equality alone and pass an IEqualityComparer<T> when a particular collection needs a different rule: new HashSet<string>(StringComparer.OrdinalIgnoreCase).

Don't change a key

A hash table files an item under its hash code when it's added. If the fields behind the hash then change, the item is stuck in the wrong slot. It's another good argument for immutable keys.

Lost in its own set C#
var item = new Mutable { Id = 1 };
var set = new HashSet<Mutable> { item };

Console.WriteLine(set.Contains(item));
item.Id = 2;
Console.WriteLine(set.Contains(item));
Console.WriteLine(set.Count);

record Mutable
{
    public int Id { get; set; }
}
Check your prediction
Text
True
False
1

Records have limits too

A record's generated equality compares each field with its own Equals. A List field compares by reference, so two records with equal contents aren't equal, as you saw at the end of the Intermediate course. If this matters, replace that one member by writing your own equality, or store something with value equality, such as a string.

Records and list fields C#
var ids = new List<int> { 1 };
Console.WriteLine(new Tagged("a", ids) == new Tagged("a", ids));
Console.WriteLine(new Tagged("a", ids) == new Tagged("a", new List<int> { 1 }));
Console.WriteLine(new Plain("a", "1") == new Plain("a", "1"));

record Tagged(string Name, List<int> Ids);

record Plain(string Name, string Ids);
Check your prediction
Text
True
False
True

Your turn

Exercise

A key type that ignores order

Write a readonly struct Edge for an undirected connection between two node numbers: new Edge(1, 2) and new Edge(2, 1) are the same edge. Implement IEquatable<Edge>, Equals(object), GetHashCode and == and !=.

Show that new Edge(1, 2) == new Edge(2, 1) is true and that new Edge(1, 2) == new Edge(1, 3) is false. Then add the edges (1,2), (2,1), (2,3) and (3,3) to a HashSet<Edge> and print its count.

When it works, it prints:

Text
True
False
3
Your workspace C#
Console.WriteLine("Start here");
Hint 1: the idea

If the constructor stores the smaller number first, equal edges have identical fields, and every other method becomes simple.

Hint 2: a first step

Math.Min and Math.Max normalize the order. Then HashCode.Combine(Low, High) agrees with an Equals that compares both fields.

Show one solution
C#
#nullable enable

Console.WriteLine(new Edge(1, 2) == new Edge(2, 1));
Console.WriteLine(new Edge(1, 2) == new Edge(1, 3));
Console.WriteLine(new HashSet<Edge> { new(1, 2), new(2, 1), new(2, 3), new(3, 3) }.Count);

readonly struct Edge(int a, int b) : IEquatable<Edge>
{
    public int Low { get; } = Math.Min(a, b);
    public int High { get; } = Math.Max(a, b);

    public bool Equals(Edge other) => Low == other.Low && High == other.High;

    public override bool Equals(object? other) => other is Edge edge && Equals(edge);

    public override int GetHashCode() => HashCode.Combine(Low, High);

    public static bool operator ==(Edge left, Edge right) => left.Equals(right);

    public static bool operator !=(Edge left, Edge right) => !left.Equals(right);
}
Text
True
False
3

Was this article helpful?

Your response is saved on this device.