Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

c# - What is the default equality comparer for a set type?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...