Resharper's GetHashCode() and the number 29

Published 07-16-2007 5:30 PM | jokiz

I blogged last year last year about Overriding Equals and GetHashCode

You provide an Equals override if you want to provide value equality on your business objects and normally, you'd use the logical key fields (DB lingo) for comparison.

GetHashCode is used by ISet (ListSet), if you used NHibernate, it'll force you to provide GetHashCode since it uses an object's hashcode as identifier for a set element.  So basically if you have two object instances with the same hashcode, they are treated as one.

With the previous post, I raised the question on what is the magic number 29 which is used by Resharper in generating GetHashCode method implementation.  Here is a sample code using _id, _category and _expression fields as logical key: 

 

       public override int GetHashCode()

        {

            int result = _id;

            result = 29*result + _category.GetHashCode();

            result = 29*result + _expression.GetHashCode();

            return result;

        }


I have just asked JetBrains support on why 29?  Here is what I got:

The number 29 is special in a way that it's a simple number, but
other than that, it doesn't have any specific properties and we could use other simple numbers like 31 etc as well. Thank you!

Filed under: , ,

Comments

# cruizer said on July 16, 2007 1:55 AM:

i thought it had something to do with 29 being a prime number :P looks like i was mistaken! ha ha

# jop said on July 16, 2007 3:13 AM:

I agree - 31 is ok. But beware of 42. It is *not* a simple number: http://en.wikipedia.org/wiki/The_Answer_to_Life,_the_Universe,_and_Everything

# cruizer said on July 16, 2007 6:35 AM:

ha ha!!!

# behemoth said on November 28, 2007 8:16 AM:

This is pretty terrible; what about overflow?

Better to xor the hash codes. No danger of overflows and faster.

# polonium said on July 4, 2008 3:44 AM:

It is pretty terrible - esp when considering objects with large amount of properties / levels  of inheritance.

31 is also a prime number.