Horje

HASH codes for common types in c - Hash Functions - Algorithm
Learn
Algorithm - Hash Functions - Hash codes for common types in c
Hash codes for common types in C#

The hash codes produced by GetHashCode() method for built-in (opens new window) and common C# types from the System namespace are shown below.

Boolean (opens new window)

1 if value is true, 0 otherwise.

Byte (opens new window), UInt16 (opens new window), Int32 (opens new window), UInt32 (opens new window), Single (opens new window)

Value (if necessary casted to Int32).

SByte (opens new window)

((int)m_value ^ (int)m_value << 8);

Char (opens new window)

(int)m_value ^ ((int)m_value << 16);

Int16 (opens new window)

((int)((ushort)m_value) ^ (((int)m_value) << 16));

Int64 (opens new window), Double (opens new window)

Xor between lower and upper 32 bits of 64 bit number

(unchecked((int)((long)m_value)) ^ (int)(m_value >> 32));

UInt64 (opens new window), DateTime (opens new window), TimeSpan (opens new window)

((int)m_value) ^ (int)(m_value >> 32);

Decimal (opens new window)

((((int *)&dbl)[0]) & 0xFFFFFFF0) ^ ((int *)&dbl)[1];

Object (opens new window)

RuntimeHelpers.GetHashCode(this);

The default implementation is used sync block index (opens new window).

String (opens new window)

Hash code computation depends on the platform type (Win32 or Win64), feature of using randomized string hashing, Debug / Release mode. In case of Win64 platform:

int hash1 = 5381;
int hash2 = hash1;
int c;
char *s = src;
while ((c = s[0]) != 0) {
    hash1 = ((hash1 << 5) + hash1) ^ c;
    c = s[1];
    if (c == 0)
        break;
    hash2 = ((hash2 << 5) + hash2) ^ c;
    s += 2;
}
return hash1 + (hash2 * 1566083941);

ValueType (opens new window)

The first non-static field is look for and get it's hashcode. If the type has no non-static fields, the hashcode of the type returns. The hashcode of a static member can't be taken because if that member is of the same type as the original type, the calculating ends up in an infinite loop.

Nullable (opens new window)

return hasValue ? value.GetHashCode() : 0;

Array (opens new window)

int ret = 0;
for (int i = (Length >= 8 ? Length - 8 : 0); i < Length; i++) 
{
    ret = ((ret << 5) + ret) ^ comparer.GetHashCode(GetValue(i));
}

References

Read Article
https://develop.horje.com/learn/1434/reference