2

Visual Studio default implementation for GetHashCode():

class Animal
{
    public int Id { get; set; }

    public override int GetHashCode()
    {
        return 2108858624 + Id.GetHashCode();
    }
}

Why "2108858624" is added to Id for GetHashCode compute?

Video: (Gif)

Image

Vinicius Gonçalves
  • 2,514
  • 1
  • 29
  • 54
  • You have to take [red pill](https://stackoverflow.com/q/263400/1997232) ([used reference](https://en.wikipedia.org/wiki/Red_pill_and_blue_pill)). – Sinatr Jan 25 '19 at 14:04
  • 2
    VS has several ways of generating code, but I'm not aware of one that produces a `GetHashCode` implementation of this kind (the best I can get it to do is produce a dummy implementation that calls `base.GetHashCode()`). How are you getting this one? – Jeroen Mostert Jan 25 '19 at 14:08
  • @JeroenMostert, I've added a little gif, see please. – Vinicius Gonçalves Jan 25 '19 at 16:09
  • 1
    Subtle stuff! VS won't give you a prompt to generate that until the class actually has a member, which is why I missed it. I don't know where it gets the number from, but it is based on the member name -- `id` and `Id` will produce different numbers. Dare I guess it's hashing them? (But no, not with a simple `String.GetHashCode()`, in case you were wondering.) If you include more members, you'll see it implements a simple multiply-and-add hash. The numbers it picks (or how it picks them) aren't really that important. (I'd criticize the omission of an `unchecked` block, though.) – Jeroen Mostert Jan 25 '19 at 16:18
  • 1
    Incidentally, the multiply factor seems to be constant: `-1521134295`. This number isn't random: it's `0b10100101010101010101010100101001` or `2773833001` if interpreted as a `uint`, and the fact that that is a prime number with a lot of alternating bits is specifically intended to 1) distribute the hashed bits of the components and 2) reduce hash collisions when a modulo is taken. The initial number may also have some clever thinking behind it that I'm not seeing, we'd have to ask the VS developers. – Jeroen Mostert Jan 25 '19 at 16:24

0 Answers0