ZetCode

C# IEquatable and equality

last modified November 15, 2026

This article shows how to implement equality in C#. We cover reference and value equality, the IEquatable<T> interface, the GetHashCode contract, equality operators, structs, records, and custom equality comparers.

C# distinguishes two kinds of equality. Reference equality means that two variables point to the same object. Value equality means that two objects hold equal data. For classes, Equals and the == operator use reference equality unless the class overrides them. Types that represent values, such as points, money amounts, or email addresses, usually need value equality.

The IEquatable<T> interface declares a single method, bool Equals(T? other). It is the strongly typed counterpart of object.Equals. Generic collections, such as List<T>, HashSet<T>, and Dictionary<TKey, TValue>, as well as LINQ methods, use it through EqualityComparer<T>.Default. The interface pairs with IComparable<T>, which defines ordering rather than equality.

Reference equality

A class that does not override equality compares references.

Program.cs
var p1 = new Point(1, 2);
var p2 = new Point(1, 2);
var p3 = p1;

Console.WriteLine(p1 == p2);
Console.WriteLine(p1.Equals(p2));
Console.WriteLine(p1 == p3);

List<Point> points = [p1];
Console.WriteLine(points.Contains(new Point(1, 2)));

class Point(int x, int y)
{
    public int X { get; } = x;
    public int Y { get; } = y;
}

We create two points with the same coordinates.

Console.WriteLine(p1 == p2);
Console.WriteLine(p1.Equals(p2));
Console.WriteLine(p1 == p3);

The points p1 and p2 are two different objects, so they are not equal. The variable p3 refers to the same object as p1.

Console.WriteLine(points.Contains(new Point(1, 2)));

The Contains method does not find the point, although the list contains a point with the same coordinates.

$ dotnet run
False
False
True
False

Implementing IEquatable

A complete value equality implementation for a class consists of four parts: the IEquatable<T>.Equals method, an override of object.Equals, an override of GetHashCode, and the == and != operators.

Program.cs
var p1 = new Point(1, 2);
var p2 = new Point(1, 2);
var p3 = new Point(3, 4);

var set = new HashSet<Point> { p1, p2, p3 };
Console.WriteLine(set.Count);

Console.WriteLine(p1 == p2);
Console.WriteLine(p1 != p3);
Console.WriteLine(p1.Equals(p2));
Console.WriteLine(p1.Equals((object)p2));
Console.WriteLine(p1.Equals(null));

class Point(int x, int y) : IEquatable<Point>
{
    public int X { get; } = x;
    public int Y { get; } = y;

    public bool Equals(Point? other)
    {
        if (other is null) return false;
        if (ReferenceEquals(this, other)) return true;

        return X == other.X && Y == other.Y;
    }

    public override bool Equals(object? obj) => Equals(obj as Point);

    public override int GetHashCode() => HashCode.Combine(X, Y);

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

    public static bool operator !=(Point? left, Point? right) => !(left == right);
}

The Point class implements value equality.

public bool Equals(Point? other)
{
    if (other is null) return false;
    if (ReferenceEquals(this, other)) return true;

    return X == other.X && Y == other.Y;
}

The typed Equals method holds the logic. An object is never equal to null. The reference check is a shortcut for comparing an object with itself.

public override bool Equals(object? obj) => Equals(obj as Point);

The override of object.Equals delegates to the typed method. The as operator gives null for objects of other types. Both methods must give the same answer.

public override int GetHashCode() => HashCode.Combine(X, Y);

Equal objects must have equal hash codes. The HashCode.Combine method mixes the hash codes of the fields that take part in the comparison.

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

The == operator must handle null on both sides. We check for null with the is pattern, because left == null would call the operator recursively. The HashSet keeps only two of the three points.

$ dotnet run
2
True
True
True
True
False

The GetHashCode contract

Hash-based collections first compare hash codes and call Equals only for elements with matching hash codes. If a type overrides Equals but not GetHashCode, these collections break.

Program.cs
var u1 = new User("john@example.com");
var u2 = new User("john@example.com");

Console.WriteLine(u1.Equals(u2));

List<User> list = [u1];
Console.WriteLine(list.Contains(u2));

var set = new HashSet<User> { u1, u2 };
Console.WriteLine(set.Count);

var dict = new Dictionary<User, string> { [u1] = "admin" };
Console.WriteLine(dict.ContainsKey(u2));

#pragma warning disable CS0659
class User(string email) : IEquatable<User>
{
    public string Email { get; } = email;

    public bool Equals(User? other) => other is not null && Email == other.Email;

    public override bool Equals(object? obj) => Equals(obj as User);
}

The User class compares by email but keeps the default GetHashCode inherited from object.

#pragma warning disable CS0659

The compiler warns about this mistake with the CS0659 warning; we disable it for the demonstration.

List<User> list = [u1];
Console.WriteLine(list.Contains(u2));

A list scans its elements and calls Equals, so it finds the user.

var set = new HashSet<User> { u1, u2 };
Console.WriteLine(set.Count);

The default hash code is based on the object identity. The two equal users get different hash codes, end up in different buckets, and the set keeps both of them. Likewise, the dictionary does not find the key. Note also that the fields used in GetHashCode should not change while the object is stored in a hash-based collection; this is one reason why value types are best made immutable.

$ dotnet run
True
True
2
False

Structs

Structs have value equality by default: ValueType.Equals compares all fields. The default implementation is slow, however. It boxes the argument and for many structs uses reflection. Structs also get no == operator; a == b does not compile.

Program.cs
var a = new Money(10m, "EUR");
var b = new Money(10m, "EUR");
var c = new Money(10m, "USD");

Console.WriteLine(a.Equals(b));
Console.WriteLine(a == b);
Console.WriteLine(a == c);
Console.WriteLine(a.GetHashCode() == b.GetHashCode());

var m1 = new Measure(1.5);
var m2 = new Measure(1.5);
Console.WriteLine(m1.Equals(m2));

readonly struct Money(decimal amount, string currency) : IEquatable<Money>
{
    public decimal Amount { get; } = amount;
    public string Currency { get; } = currency;

    public bool Equals(Money other) =>
        Amount == other.Amount && Currency == other.Currency;

    public override bool Equals(object? obj) => obj is Money m && Equals(m);

    public override int GetHashCode() => HashCode.Combine(Amount, Currency);

    public static bool operator ==(Money left, Money right) => left.Equals(right);
    public static bool operator !=(Money left, Money right) => !left.Equals(right);
}

struct Measure(double value)
{
    public double Value { get; } = value;
}

The Money struct implements IEquatable<Money> and the operators. The Measure struct relies on the defaults.

public bool Equals(Money other) =>
    Amount == other.Amount && Currency == other.Currency;

For a struct, the typed method takes a non-nullable parameter; a struct cannot be null. Generic collections call this method directly, without boxing.

public override bool Equals(object? obj) => obj is Money m && Equals(m);

The as operator cannot be used with structs, so the override uses a type pattern.

Console.WriteLine(m1.Equals(m2));

The default equality of Measure works, but each call goes through ValueType.Equals. Implementing IEquatable<T> is recommended for every struct that is compared or used as a dictionary key.

$ dotnet run
True
True
False
True
True

Records

Records generate all the equality members automatically: they implement IEquatable<T>, override Equals and GetHashCode, and define the == and != operators.

Program.cs
var c1 = new City("Bratislava", 475_000);
var c2 = new City("Bratislava", 475_000);

Console.WriteLine(c1 == c2);
Console.WriteLine(c1.Equals(c2));
Console.WriteLine(c1.GetHashCode() == c2.GetHashCode());
Console.WriteLine(c1 is IEquatable<City>);

var t1 = new Team("Falcons", ["Ann", "Bob"]);
var t2 = new Team("Falcons", ["Ann", "Bob"]);

Console.WriteLine(t1 == t2);

var t3 = t1 with { };
Console.WriteLine(t1 == t3);

record City(string Name, int Population);

record Team(string Name, string[] Members);

We compare two records with the same values.

Console.WriteLine(c1 is IEquatable<City>);

The generated record implements the interface. Equality compares the values of all fields.

var t1 = new Team("Falcons", ["Ann", "Bob"]);
var t2 = new Team("Falcons", ["Ann", "Bob"]);

Console.WriteLine(t1 == t2);

The generated code compares each field with EqualityComparer<T>.Default. Arrays use reference equality, so two teams with different arrays of the same members are not equal. When a record contains a collection, we write our own Equals(Team? other) and GetHashCode, for instance with SequenceEqual.

var t3 = t1 with { };
Console.WriteLine(t1 == t3);

The copy made by the with expression shares the same array instance, so the records are equal.

$ dotnet run
True
True
True
True
False
True

Equality comparers

Sometimes we need a different notion of equality than the type defines, or the type is not ours. An IEqualityComparer<T> object supplies the equality logic from outside. Collections and LINQ methods accept comparers as arguments.

Program.cs
string[] words = ["Sky", "sky", "Cup", "SKY", "cup", "war"];

var unique = words.Distinct(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(string.Join(" ", unique));

var byLength = EqualityComparer<string>.Create(
    (a, b) => a?.Length == b?.Length,
    s => s.Length);

string[] birds = ["owl", "falcon", "eagle", "hawk", "kestrel", "heron", "kite"];
Console.WriteLine(string.Join(" ", birds.Distinct(byLength)));

var products = new HashSet<Product>(new ProductCodeComparer())
{
    new("A-1", "pen"),
    new("a-1", "pen, blue"),
    new("B-2", "ink")
};

Console.WriteLine(products.Count);

record Product(string Code, string Name);

class ProductCodeComparer : IEqualityComparer<Product>
{
    public bool Equals(Product? x, Product? y) =>
        string.Equals(x?.Code, y?.Code, StringComparison.OrdinalIgnoreCase);

    public int GetHashCode(Product p) =>
        StringComparer.OrdinalIgnoreCase.GetHashCode(p.Code);
}

We use a built-in comparer, a comparer created from lambdas, and a custom comparer class.

var unique = words.Distinct(StringComparer.OrdinalIgnoreCase);

The StringComparer class provides ready-made comparers for strings. The words are compared without regard to case; the first occurrence of each word is kept.

var byLength = EqualityComparer<string>.Create(
    (a, b) => a?.Length == b?.Length,
    s => s.Length);

The EqualityComparer<T>.Create method, added in .NET 8, builds a comparer from an equality function and a hash function. Words are considered equal if they have the same length, so only the first word of each length is kept.

public int GetHashCode(Product p) =>
    StringComparer.OrdinalIgnoreCase.GetHashCode(p.Code);

The ProductCodeComparer compares products by their code, ignoring case. The hash code must be computed in the same case-insensitive way; p.Code.GetHashCode() would give different hash codes for A-1 and a-1.

$ dotnet run
Sky Cup war
owl falcon eagle hawk kestrel
2

Which Equals is called

The EqualityComparer<T>.Default property checks whether T implements IEquatable<T>. If it does, the comparer calls the typed method; otherwise it falls back to object.Equals.

Program.cs
var items = new List<Item> { new(1), new(2), new(3) };

Console.WriteLine(items.Contains(new Item(3)));
Console.WriteLine(items.IndexOf(new Item(2)));

object o = new Item(1);
Console.WriteLine(o.Equals(new Item(1)));

Console.WriteLine(EqualityComparer<Item>.Default.GetType().Name);

class Item(int id) : IEquatable<Item>
{
    public int Id { get; } = id;

    public bool Equals(Item? other)
    {
        Console.WriteLine($"  IEquatable<Item>.Equals({Id}, {other?.Id})");
        return other is not null && Id == other.Id;
    }

    public override bool Equals(object? obj)
    {
        Console.WriteLine($"  object.Equals({Id})");
        return Equals(obj as Item);
    }

    public override int GetHashCode() => Id;
}

Both Equals methods of the Item class print a message when called.

Console.WriteLine(items.Contains(new Item(3)));

The Contains method calls the typed method for each element until it finds a match.

object o = new Item(1);
Console.WriteLine(o.Equals(new Item(1)));

Through an object reference, only the override of object.Equals is available; it then delegates to the typed method.

Console.WriteLine(EqualityComparer<Item>.Default.GetType().Name);

For types implementing IEquatable<T>, the default comparer is a GenericEqualityComparer<T>. For other types it is an ObjectEqualityComparer<T>.

$ dotnet run
  IEquatable<Item>.Equals(1, 3)
  IEquatable<Item>.Equals(2, 3)
  IEquatable<Item>.Equals(3, 3)
True
  IEquatable<Item>.Equals(1, 2)
  IEquatable<Item>.Equals(2, 2)
1
  object.Equals(1)
  IEquatable<Item>.Equals(1, 1)
True
GenericEqualityComparer`1

Source

IEquatable<T> interface

How to define value equality for a class or struct

In this article we have implemented equality in C#. See also the IComparable, record, HashSet, and StringComparison tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.