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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With