Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why HashSets with same elements return different values when calling to GetHashCode()?

Why HashSet<T>.GetHashCode() returns different hashcodes when they have the same elements?

For instance:

[Fact]
public void EqualSetsHaveSameHashCodes()
{
    var set1 = new HashSet<int>(new [] { 1, 2, 3 } );
    var set2 = new HashSet<int>(new [] { 1, 2, 3 } );

    Assert.Equal(set1.GetHashCode(), set2.GetHashCode());
}

This test fails. Why?

How can I get the result I need? "Equal sets give the same hashcode"

like image 529
SuperJMN Avatar asked Oct 21 '25 15:10

SuperJMN


1 Answers

HashSet<T> by default does not have value equality semantics. It has reference equality semantics, so two distinct hash sets won't be equal or have the same hash code even if the containing elements are the same.

You need to use a special purpose IEqualityComparer<HashSet<int>> to get the behavior you want. You can roll your own or use the default one the framework provides for you:

var hashSetOfIntComparer = HashSet<int>.CreateSetComparer();

//will evaluate to true
var haveSameHash = hashSetOfIntComparer.GetHashCode(set1) ==
                   hashSetOfIntComparer.GetHashCode(set2);

So, to make a long story short:

How can I get the result I need? "Equal sets give the same hashcode"

You can't if you are planning on using the default implementation of HashSet<T>.GetHashCode(). You either use a special purpose comparer or you extend HashSet<T> and override Equals and GetHashCode to suit your needs.

like image 137
InBetween Avatar answered Oct 23 '25 05:10

InBetween