Saturday, July 28, 2012

Strange fact about GetHashCode()

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:
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.