7

In this example, the poster has overridden the get hash code method. I understand that this has been done in order to provide a better hash value for the returned object, to reduce the number of collisions, and therefore reduce the number of occasions it will be necessary to call Equals().

What i would like to know, is how this algorithm been calculated:

return 17 + 31 * CurrentState.GetHashCode() + 31 * Command.GetHashCode();

Is there a particular reason that the numbers in question were chosen? Could i have simply picked my own numbers to put into it?

asked May 31, 2011 at 10:41
5
  • 1
    Just for info, the MS C# compiler (for anon-types) uses a seed of -1134271262, and a multiplier of -1521134295. Just sayin' Commented May 31, 2011 at 10:48
  • @MarcGravell: Do you have the source for that? Commented Jun 25, 2014 at 3:01
  • @DeepSpace101 ILDASM ;p Commented Jun 25, 2014 at 6:50
  • @MarcGravell: I see the same -1521134295 multiplier in ILDASM but the seed appears to be a composite seed (it's a random int32 multiplied by the same multiplier). So the seed's not only NOT prime (contrary to popular belief), it's also random based on the anon-type member names/type/count. Weird. Any ideas why? Commented Jun 25, 2014 at 18:38
  • @DeepSpace none. Interesting. Commented Jun 25, 2014 at 18:40

3 Answers 3

4

Generally you should choose primes. This helps you to avoid getting the same hash-value for different input parameters.

answered May 31, 2011 at 10:43
2

Prime numbers are usually used in hashcode computation to minimize the collisions. If you search for hashcode and prime numbers on this iste, you will find some detailed explanations on this (note that it is note language specific):

answered May 31, 2011 at 10:44
1

You typically want to use prime numbers (as is done above) because it reduces the chance of collisions (two instances yielding same result). For more info, see: http://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/

answered May 31, 2011 at 10:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.