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
- Implementing IEquatable
- Overriding GetHashCode
- Implementing IComparable
- IComparer for Custom Sorting