views:

46

answers:

1

Hello, I am writing a test for my library written in C#. And I want to test whether two list are same if and only if they have same elements(do not require elements in the same order). I try to convert list to hashset and check whether the two hashset are same. But the running result is not what I expected.

Could anyone explain how the hashset contains method works? Does it compare two objects by the objects getHashCode method or equals method? Thanks!

+1  A: 

It uses the IEqualityComparer<> that you passed to the HashSet constructor. If you didn't pass one then it uses EqualityComparer<>.Default. Which, if the element type doesn't implement IEquatable<> uses the Equals and GetHashCode methods of the type.

I would guess that your list contains objects that don't override these methods. Use the IEqualityComparer constructor argument to fix.

Hans Passant