Search code examples
c#.nethashportability

Is the .NET string hash function portable?


Possible Duplicate:
How do I create a HashCode in .net (c#) for a string that is safe to store in a database?

I use C# 4.0 and gets the string hash by invoking:

"my string".GetHashCode()

Code generated by this call is stored into database to future use. This hash code is used to find some subset of strings and then to equal comparison.

Questions are:

  1. Is it a standardized hash calculation? May I assume that it is possible to calculate the same hash in different environments like C# in .Net 3.0 or future .Net editions?
  2. Is it possible to calculate the same hash function on yourself by writing it in Java, PL/SQL, Ruby, etc?
  3. Can I assume that hash generated today will be the same tomorrow in the same environment? For example when I shutdown my computer and run the program again, or change locale, or some other settings?
  4. What are the limits of portability?
  5. I know I can do it yourself, but maybe some kind of portability is provided?

Solution

  • From MSDN:

    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.

    So no, you cannot assume that the value produced by GetHashCode is stable. This isn't just theoretical, either - we've seen the value change in the past.

    If you want a stable hash, you'll have to generate it yourself.