Search code examples
c#hashcodegethashcodehash-code-uniqueness

Can GetHashCode() for the same double result in a different integer?


Is it possible for the GetHashCode() method to return different integer values for the same double value on different computers, operating systems, or architectures? For example, if I have the following code:

    public unsafe override int GetHashCode() {
        double d = m_value; 
        if (d == 0) { 
            // Ensure that 0 and -0 have the same hash code
            return 0; 
        }
        long value = *(long*)(&d);
        return unchecked((int)value) ^ ((int)(value >> 32));
    }

Could hash1 be a different integer on a different computer or operating system than it is on the original computer? Is the behavior of GetHashCode() for double values consistent across different environments?


Solution

  • Object.GetHashCode Method says:

    The default implementation of the GetHashCode method does not guarantee unique return values for different objects. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes.