GetHashcode - Int too small capacity?

Right now I’m implementing a Vector3 struct only with INTs. i did some research to figure out how to write a proper hashcode for 3 Ints, and i stumbled upon this page (also referenced by many other pages talking about hashcodes):

public override int GetHashCode()
{
   unchecked // Overflow is fine, just wrap
   {
       int hash = 17;
       // Suitable nullity checks etc, of course :)
       hash = hash * 23 + field1.GetHashCode();
       hash = hash * 23 + field2.GetHashCode();
       hash = hash * 23 + field3.GetHashCode();
       return hash;
   }
}

Now, i implemented the HashCode as follows:

        public override int GetHashCode()
        {
            int hash = 17;

            hash = hash * 486187739 + x.GetHashCode();
            hash = hash * 486187739 + y.GetHashCode();
            hash = hash * 486187739 + z.GetHashCode();
            return hash;
        }

My question is - the number returned is incredibly large, and can actually not be stored in the returned INT. How come, this is the suggested prime number then? Am i missing an important step in the implementation?

Cheers and thanks upfront!

I think it will just truncate/overflow silently, if the number cannot fit.
Provided overflow checking is disabled or if enabled, the code is written inside a ‘checked’ statement.

1 Like

Yes. You removed “unchecked”. The “unchecked” keyword is what makes it ignore the overflow and return anyway. If you get rid of that, it’s going to throw an OverflowException.

1 Like

@methos5k @makeshiftwings
Thanks a lot! That makes much more sense now! :).

:slight_smile: Awesome.