What is the default equality comparer for a set type?

It means it will use the comparer returned by EqualityComparer<T>.Default for the element type T of the set.

As the documentation states:

The Default property checks whether type T implements the
System.IEquatable interface and, if so, returns an
EqualityComparer that uses that implementation. Otherwise, it
returns an EqualityComparer that uses the overrides of
Object.Equals and Object.GetHashCode provided by T.

So for your custom type, it will use the GetHashCode method you have defined to locate items in the set. If you have implemented IEquatable<T> it will use IEquatable<T>.Equals(T) for equality, otherwise it will use your Equals(object) method. This method defaults to reference equality as defined in the object class. Therefore if you are defining equality using either method, you should ensure you also override GetHashCode as well.

Leave a Comment