0

Possible Duplicate:
Create a hashcode of two numbers

I have following class:

public struct Test
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }

    public override int GetHashCode()
    {
        return Prop1.GetHashCode() ^ Prop2.GetHashCode();
    }
}

Today I found out that I'm computing GetHashCode in a wrong way - if both properties are the same it always returns 0. How to do it the right way?

Community
  • 1
  • 1
Poma
  • 8,118
  • 16
  • 59
  • 137
  • I don't think it's a dupe of that one - that one is all about creating a hash for a 2d point space. This one is about creating a hash of a class with multiple string properties. – bryanmac Oct 01 '11 at 14:44
  • Yep, that's. Question can be closed. – Poma Oct 01 '11 at 14:47
  • OK - that one is better. Agreed. – bryanmac Oct 01 '11 at 14:48
  • Another suggestion - do it Resharper's way: http://stackoverflow.com/questions/102742/why-is-397-used-for-resharper-gethashcode-override – Ilian Oct 01 '11 at 14:49

1 Answers1

4

There is no single correct way to implement GetHashCode. Since your properties are strings there are an infinate number of possible combinations of values. The hash code is an Int32 so there only 2^32 possible values. Therefore, the HashCode cannot be unique for every possible value of Prop1 & Prop2. You have discovered one point where the value repeats and that is where Prop1 = Prop2. The idea of the hash code is that you get a fairly even distribution of values based upon the data you are expecting. If you exepect prop1 and prop2 to rarley be equal during execution, then its probably not an issue. However, if you expect prop1 and prop2 to be equal most of the time, then you should probably use a different algorithim for the hash code.

user957902
  • 2,890
  • 11
  • 17