While doing one of my assignment, I came across a strange fact about GetHashCode() in C#. Object.GetHashCode() tells that String class returns identical hash codes for identical strings. But after doing some experiments, I found that above mentioned statement is bit misleading. Actually, it varies from architecture-to-architecture, depending upon, whether one is using 32-bit or 64-bit machine. To prove this, I created a sample application in C#.
I ran above snippet on 32-bit windows machine and found below result:
I ran above snippet on 32-bit windows machine and found below result:
then I ran the same code on 64-bit machine and come up with below result:
Now looking at above results, one can easily conclude about the behaviour of GetHashCode(). So, beware and think atleast twice, before using GetHashCode() for strings, as it may give different-different results on different-different platforms.
"Object.GetHashCode() tells that String class returns identical hash codes for identical strings"
ReplyDeletethis statement points to
string first = "Hello";
string second = "Hello";
first.GetHashCode() == second.GetHashCode()
This is called "string interning"
not with platform architecture
I think, you misunderstood my article. Here my aim was to generate hash code of a given string ("Shweta") on both 64 and 32-bit machine and as a result I found that both the architectures are generating different-different hash codes. There is nothing to do with string interning.
DeleteHope I am clear now :)