Why this code return unique hash code RRS feed

  • Question


    My question

    Q1: Why this code return unique hash code. How it works ? I can't understand.

    Q2: why hash is 17 ?

    Q3: why it multiple by 23 ?

    Q4: why previous value multiple by 23 + next value hash code return unique hash code ?

    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;

    Media Store

    Thursday, June 1, 2017 10:27 AM


  • Firstly hashes aren't guaranteed unique. Never have been. A hash is as unique as you can make it. In the best case it is completely unique but more likely it is only unique for the values you happen to be storing (e.g. in the dictionary).

    When creating a hash value your goal is to make the value as unique as possible. To be honest creating good hash functions is hard and not recommended. To produce a good hash value the hash for 2 instances with the same values should be the same (at least for value types which is what it appears this code you got came from). If even one value is different then the hashes should be different. Therefore standard practice for value types is to combine the hash code of each of the fields (of course value type fields are expected to be immutable).

    Since this was originally posted in SO you should refer to that thread for the rationale. In that thread there is a link to an article on how to properly implement GetHashCode. The book Effective C# also has an entire section dedicated to it. You should read both of these to understand the importance of GetHashCode and when you should implement it. Furthermore the SO post provides a link to the hash code algorithm that was posted. You should follow that link and read the original author's rationale about why the aforementioned code works. There is no benefit in us posting that same rationale here. Is it a good algorithm? I don't know. You'd have to throw a bunch of tests at it to figure out. There are several different algorithms available. I wouldn't recommend that you implement your own.

    Michael Taylor

    • Marked as answer by SmartWhy Saturday, June 3, 2017 5:27 AM
    Thursday, June 1, 2017 2:02 PM