C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
So: The hash computation appears to be effective—no collisions are seen when we just append a character.
C# program that uses GetHashCode
using System;
class Program
{
static void Main()
{
string value = "";
for (int i = 0; i < 10; i++)
{
value += "x";
// This calls the unsafe code listed on this page.
Console.WriteLine("GETHASHCODE: " + value.GetHashCode());
}
}
}
Output
GETHASHCODE: -842352680
GETHASHCODE: -838682664
GETHASHCODE: -126710822
GETHASHCODE: 1988791258
GETHASHCODE: 847333320
GETHASHCODE: 844711880
GETHASHCODE: 1653319342
GETHASHCODE: -1698453842
GETHASHCODE: -795746332
GETHASHCODE: -803610652
Tip: Hash codes are used in Dictionary instances and other associative collections.
DictionaryAnd: This method is located in mscorlib. It is invoked in every program that uses a Dictionary or Hashtable using C# or VB.NET.
Note: It uses several magic constants and low-level pointer arithmetic to achieve its performance requirement.
String GetHashCode method implementation: C#
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override unsafe int GetHashCode()
{
fixed (char* str = this)
{
char* chPtr = str;
int num = 352654597;
int num2 = num;
int* numPtr = (int*)chPtr;
for (int i = this.Length; i > 0; i -= 4)
{
num = (((num << 5) + num) + (num >> 27)) ^ numPtr[0];
if (i <= 2)
{
break;
}
num2 = (((num2 << 5) + num2) + (num2 >> 27)) ^ numPtr[1];
numPtr += 2;
}
return (num + (num2 * 1566083941));
}
}
Note: Using the unsafe keyword also has higher security demands on executables. The built-in GetHashCode method avoids these problems.
Note: Once you apply the fixed keyword to the context, you can use pointer arithmetic on the string's internal character vector.
FixedNote: By shifting bits in a hash computation, we avoid funneling. This is where the computations made later erase those made previously.
ShiftCorrection: This article previously had an error in the section on bit manipulations. Bret Mulvey wrote in with the correct information.