Implementing the IEqualityComparer of T interface for object equality with C# .NET

The generic IEqualityComparer of T provides you a way to indicate whether two custom objects are equal. We’ve looked at equality in a number of posts on this blog – see the link below if you’re curious – and IEqualityComparer fulfils a similar purpose though its usage is different.

Equality comparers are most often used to filter out duplicates from a collection.

Let’s say that two triangles are equal if their areas are the same. IEqualityComparer comes with two methods to be implemented: Equals and GetHashCode. GetHashCode returns an integer and two objects that are equal should return the same value. Here’s an IEqualityComparer implementation:

Instead of implementing IEqualityComparer you can derive from the EqualityComparer base class which implements the generic IEqualityComparer of T and the non-generic IEqualityComparer interface. The implementation is very similar to the one above: