What is the default equality comparer for a set type?

后端 未结 2 583
情歌与酒
情歌与酒 2020-12-09 03:03

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 d

相关标签:
2条回答
  • 2020-12-09 03:27

    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.

    0 讨论(0)
  • 2020-12-09 03:40

    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:

    • if the class implements IEquatable<T>, it will delegate to the class's implementation of this interface
    • if the class has an Equals method defined, it will use that
    • as a last resort, it will use reference equality
    0 讨论(0)
提交回复
热议问题