0Pricing
C# Academy · Lesson

Implementing IEquatable

Provide type-safe equality with Equals.

Why IEquatable<T>?

IEquatable<T> provides a strongly typed Equals(T other) method. It avoids boxing for value types and avoids casting for reference types, making equality both faster and clearer.

Implementing the Interface

Implement IEquatable<T> and provide Equals(T other). You should also override the inherited object.Equals and GetHashCode to keep all paths consistent.

using System;

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

    public bool Equals(Point other) => X == other.X && Y == other.Y;
    public override bool Equals(object obj) => obj is Point p && Equals(p);
    public override int GetHashCode() => HashCode.Combine(X, Y);
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine(new Point(1, 2).Equals(new Point(1, 2)));
    }
}

All lessons in this course

  1. Implementing IEquatable
  2. Overriding GetHashCode
  3. Implementing IComparable
  4. IComparer for Custom Sorting
← Back to C# Academy