What is the default equality comparer for a set type?

后端 未结 2 593
情歌与酒
情歌与酒 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.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 it will use IEquatable.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.

提交回复
热议问题