In the MSDN API for the HashSet
constructor with no arguments it states
Initializes a new instance of the HashSet class that is empty and uses the default equality comparer for the set type.
What is the default equality comparer for the set type, e.g. for a custom class?
BTW: Is it just me or is the MSDN API documentation really a bit thin on explanations? I stumble about such questions more than once when reading it.
IComparable interface, then the default comparer is the IComparable. CompareTo(Object) method of that interface. If type T doesn't implement either interface, then there is no default comparer, and a comparer or comparison delegate must be provided explicitly.
With value types, you should always override the == operator. Like the Equals method, the default implementation of the == operator uses reflection and is slow. Use the same logic as the Equals method, and you'll get much better performance when you're doing equality comparisons on value types.
The Distinct extension method returns a new collection of unique elements from the given collection. The Distinct extension method doesn't compare values of complex type objects. You need to implement IEqualityComparer<T> interface in order to compare the values of complex types.
The most common way to compare objects in C# is to use the == operator. For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object.
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 byT
.
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.
By default, it will delegate to EqualityComparer<T>.Default
. This returns a comparer that can compare two objects of type T
.
For a custom class, this does a few things in this order:
IEquatable<T>
, it will delegate to the class's implementation of this interfaceEquals
method defined, it will use thatIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With