I am trying to create a quick hashcode function for a complex number class (a + b) in C#.
I have seen repeatedly the a.GetHashcode()^b.GetHashCode() method.
But this will give the same hashcode for (a,b) and (b,a).
Are there any standard algorithm to do this and are there any functions in the .Net framework to help?
My normal way of creating a hashcode for an arbitrary set of hashable items:
In your case
item1Hashcould just bea, anditem2Hashcould just beb.The values of 23 and 31 are relatively unimportant, so long as they’re primes (or at least coprime).
Obviously there will still be collisions, but you don’t run into the normal nasty problems of:
If you know more about what the real values of
aandbare likely to be you can probably do better, but this is a good initial implementation which is easy to remember and implement. Note that if there’s any chance that you’ll build the assembly with “check for arithmetic overflow/underflow” ticked, you should put it all in an unchecked block. (Overflow is fine for this algorithm.)