Vaguely about different implementations of GetHashCode () for short and short

Consider the following code:

private static void TestHashCode<T>() { dynamic initialValue = 10; Console.WriteLine("{0}: {1}", typeof(T).Name, ((T)initialValue).GetHashCode()); } TestHashCode<int>(); TestHashCode<uint>(); TestHashCode<long>(); TestHashCode<ulong>(); TestHashCode<short>(); TestHashCode<ushort>(); 

Output:

 Int32: 10 UInt32: 10 Int64: 10 UInt64: 10 Int16: 655370 UInt16: 10 

See the difference between short and ushort ? Indeed, the source code for these classes is different:

 // ushort public override int GetHashCode() { return (int) this; } // short public override int GetHashCode() { return (int) (ushort) this | (int) this << 16; } 

But at the same time, GetHashCode() implementations for signed / unsigned versions of int and long are equal:

 // int and uint public override int GetHashCode() { return (int) this; } // long and ulong public override int GetHashCode() { return (int) this ^ (int) (this >> 32); } 

Could you explain why there is a difference between the short and ushort GetHashCode() ?

+7
hashcode primitive-types
source share
1 answer

in ushort GetHashCode () when this = 10;

"return (int) (ushort) this | (int) this <16;"

gives 0x0000000a | 0x000a0000 => 0x000a000a = 655370

in long and oolong "return (int) this ^ (int) (this is → 32);" gives 0x0000000a xor 0x00000000 ==> 0x0000000a = 10;

so I assume that one of the "GetHashCode" has the wrong implementation.

-one
source share

All Articles