GetHashCode() gives different results on different servers?

后端 未结 4 772
南笙
南笙 2020-12-01 16:31

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,

相关标签:
4条回答
  • 2020-12-01 17:13

    For your custom classes to return a stable hash code you should override the GetHashCode() method or else the GetHashCode method of the Object class will be used, which I think can vary a lot. (Might even be instance specific).

    0 讨论(0)
  • It's possible that you're using 2 different versions of .Net. This behavior is noted on the MSDN article:
    http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx
    From the remarks:

    The default implementation of the GetHashCode method does not guarantee unique return values for different objects. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes.

    0 讨论(0)
  • 2020-12-01 17:27

    If you need to have a checksum that e.g. allows you to quickly verify data integrity in transport, simply run it through a (cryptographic) hash with appropriate number of bits, as

    - MD5
    - SHA256
    - SHA1
    - fletcher
    

    .Net's GetHashCode is not meant to identify anything (32 bits is going to result in collisions very soon anyway, which is why you can't use it to identify string anyway.)

    Note that even the above four will allow collisions (but less soon); so be sure to only use it as a checksum, not identification.

    0 讨论(0)
  • 2020-12-01 17:32

    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/

    0 讨论(0)
提交回复
热议问题