While working on one of my assignments, I came across a strange fact about the GetHashCode() in C#. The Object.GetHashCode() says that the String class returns identical hash codes for identical strings. But after doing some experiments, I found out that the above mentioned statement is bit misleading.
Actually, it varies from architecture-to-architecture, depending upon, whether one is using a 32-bit or a 64-bit machine. To prove this, I created a sample application in C#.
class Program
{
static void Main(string[] args)
{
string myName = "shweta";
Console.WriteLine("string shweta has Hashcode: {0}",
myName.GetHashCode());
Console.ReadLine();
}
}
I ran the above snippet on a 32-bit windows machine and found the given below result:
Then, I ran the same code on a 64-bit machine and came up with this given below result:
Now looking at the above results, one can easily conclude about the behavior of the GetHashCode(). So, beware and think at least twice, before using the GetHashCode() for the strings, as it may give out different results on different platforms.