How do the GetHashCode methods work for the value types in C#? -


can ever expect same hash code situations integer has same value, cast different integer type?

what floating point numbers?

in cases pair of identical values integer cast 1 type return same hash code, behaviour should not relied on.

for pair of values same number represented float , double, value (always?) different.

from microsoft source code page: http://referencesource.microsoft.com/

uint16.gethashcode:

internal ushort m_value; // returns hashcode uint16 public override int gethashcode() {     return (int)m_value; } 

int16.gethashcode:

internal short m_value; // returns hashcode int16 public override int gethashcode() {     return ((int)((ushort)m_value) | (((int)m_value) << 16)); } 

uint32.gethashcode:

internal uint m_value; public override int gethashcode() {     return ((int) m_value); } 

int32.gethashcode:

internal int m_value; public override int gethashcode() {     return m_value; } 

int64.gethashcode:

internal long m_value; // value of lower 32 bits xored uppper 32 bits. public override int gethashcode() {     return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32)); } 

uint64.gethashcode

internal ulong m_value; // value of lower 32 bits xored uppper 32 bits. public override int gethashcode() {     return ((int)m_value) ^ (int)(m_value >> 32); } 

double.gethashcode

internal double m_value; //the hashcode double absolute value of integer representation //of double. // [system.security.securitysafecritical] public unsafe override int gethashcode() {     double d = m_value;     if (d == 0) {         // ensure 0 , -0 have same hash code         return 0;     }     long value = *(long*)(&d);     return unchecked((int)value) ^ ((int)(value >> 32)); } 

single.gethashcode

internal float m_value; [system.security.securitysafecritical]  // auto-generated public unsafe override int gethashcode() {     float f = m_value;     if (f == 0) {         // ensure 0 , -0 have same hash code         return 0;     }     int v = *(int*)(&f);     return v; } 

Comments