1

I have two hash sets that I've constructed in different ways that contain all the enum values.

    setWithAllEnums.Equals(setToTest); //  Returns false

    !(setWithAllEnums.Except(setToTest).Any());  //  Returns True


Why are these not equivalent? Does .NET not provide a GetHashCode for Enums?

Fredrick
  • 1,210
  • 2
  • 15
  • 24

1 Answers1

8

HashSet<T> doesn't override Equals. Even if two hash sets contain exactly the same values they are still unequal if they refer to different objects. The method you want is SetEquals.

Tim Schmelter makes an excellent point though. x.SetEquals(y) and !x.Except(y).Any() are not the same thing either. The sets x = {1, 2} and y = {1, 2, 3} are not equal, but !x.Except(y).Any() is true. x.SetEquals(y) is equivalent to !x.Except(y).Any() && !y.Except(x).Any().

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • @ReedCopsey: Your claim in your deleted comment to your deleted answer that hash sets proffer up their contents in a sorted order is false. Try it. `var s1 = new HashSet() { "X", "Y" }; var s2 = new HashSet() { "Y", "X" }; Console.WriteLine(s1.SequenceEqual(s2));` This produces false. Hash sets in practice produce the items *in the order they were added*. Note that they are not *guaranteed* to do that; it is an undocumented implementation detail and subject to change. – Eric Lippert Apr 12 '13 at 16:07
  • I glossed over SetEquals thinking it was a setter. Thanks! – Fredrick Apr 12 '13 at 17:35