Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I depend on the values of GetHashCode() to be consistent?

Tags:

c#

hash

Is the return value of GetHashCode() guaranteed to be consistent assuming the same string value is being used? (C#/ASP.NET)

I uploaded my code to a server today and to my surprise I had to reindex some data because my server (win2008 64-bit) was returning different values compared to my desktop computer.

like image 997
public static Avatar asked Sep 09 '08 22:09

public static


People also ask

Is hash code always the same?

The hash code itself is not guaranteed to be stable. Hash codes for identical strings can differ across versions of the . NET Framework and across platforms (such as 32-bit and 64-bit) for a single version of the . NET Framework.

What is the purpose of GetHashCode?

The GetHashCode method provides this hash code for algorithms that need quick checks of object equality. For information about how hash codes are used in hash tables and for some additional hash code algorithms, see the Hash Function entry in Wikipedia. Two objects that are equal return hash codes that are equal.

Is string GetHashCode unique?

No it is not unique. GetHashCode returns an Integer which has 2^32 possible values. However, there are clearly more than 2^32 strings that you could possibly construct. This guarantees that it cannot be unique.

Is GetHashCode unique C#?

NO! A hash code is not an id, and it doesn't return a unique value. This is kind of obvious, when you think about it: GetHashCode returns an Int32 , which has “only” about 4.2 billion possible values, and there's potentially an infinity of different objects, so some of them are bound to have the same hash code.


1 Answers

If I'm not mistaken, GetHashCode is consistent given the same value, but it is NOT guaranteed to be consistent across different versions of the framework.

From the MSDN docs on String.GetHashCode():

The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another. A reason why this might happen is to improve the performance of GetHashCode.

like image 189
Jonas Avatar answered Oct 09 '22 03:10

Jonas