0

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?

Vahid
  • 5,144
  • 13
  • 70
  • 146

1 Answers1

2

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.

NP3
  • 1,114
  • 1
  • 8
  • 15
  • While true, this is not relevant to the question, because `double` overrides `GetHashCode` implementation. And even if it did not - `ValueType` overrides `GetHashCode` of object (and double is struct). – Evk May 12 '17 at 11:25
  • @Evk So still it is possible for double.GetHashCode() to return two different integers on different .Net? I'm confused. – Vahid May 12 '17 at 11:27
  • 1
    @Vahid there is no such requirement, so you never can be sure. Full .NET framework may do one thing, .NET core might do another thing, mono might do yet another one. Or they might all do the same thing now, and in next version this can change. – Evk May 12 '17 at 11:28
  • Thanks. I understand now. – Vahid May 12 '17 at 11:30