C# Interview Question #102
What is IEquatable<T>, and when should it be implemented?
Types, Equality, Immutability & Internals Senior Advanced
Quick Interview Answer
IEquatable<T> defines a strongly typed Equals(T?) method for value equality. It avoids relying only on object.Equals and can reduce boxing for value types.
Detailed Explanation
IEquatable<T> defines a strongly typed Equals(T?) method for value equality. It avoids relying only on object.Equals and can reduce boxing for value types.
It is useful when a custom class or struct has clear logical equality semantics and equality comparisons are common.
When implementing IEquatable<T>, developers should also correctly override Equals(object?) and GetHashCode, and consider equality operators if appropriate.
Code Example
public sealed class ProductCode : IEquatable<ProductCode>
{
public string Value { get; }
public ProductCode(string value) => Value = value;
public bool Equals(ProductCode? other) =>
other is not null && Value == other.Value;
public override bool Equals(object? obj) =>
obj is ProductCode other && Equals(other);
public override int GetHashCode() => Value.GetHashCode();
}