GetHashCode() gives different results on different servers?

John picture John · May 24, 2011 · Viewed 7.3k times · Source

I declared a C# line of code like so

int hashcode = "apple".GetHashCode();

On my computer, a computer at work, and a friend's computer, the result was 1657858284. On a development server, the result was 1548091822. Is there a way for me to tell the project to always make GetHashCode() yield 1657858284, regardless of which server it is on?

more notes At first, i noticed there was a difference in versions...the 1657858284 results came from .NET 3.5 and .NET 4.0. The 1548091822 came from .NET 2.0.

I then told visual studios 2010 to compile project as a .net 2.0 project, but it still gave me 1657858284.

Answer

Eric Lippert picture Eric Lippert · May 24, 2011

As others have noted, that is in accordance with the documentation. You must not rely on GetHashCode returning the same thing, ever. The only invariant you can rely upon is that it will return the same value on the same object in the same appdomain if the object has not been mutated in any way that changes its equality semantics. If any of those conditions are not met -- if the two objects are in different appdomains, or the object was mutated in a way that changes its equality semantics -- then you have no guarantee whatsoever that "identical" objects will return the same hash code.

The only thing you should be using a hash code for is to balance a hash table. Any other usage is "off label" and at your own risk. Don't do it. If you need a stable string hash that works across arbitrary boundaries then use an industry standard algorithm like SHA256 or something.

See my archive of articles about hashing issues for more details if this subject interests you:

http://blogs.msdn.com/b/ericlippert/archive/tags/hashing/