18

I tried with batch of random strings, all values I got are positive, but I wondering:

Will String.GetHashCode() return negative or 0?

Since the return value is int, so I guess it might be, so if it is the case, I have to change my logic.

If you have answer or have some official sources, please share

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Eric Yin
  • 8,737
  • 19
  • 77
  • 118

2 Answers2

30

Yes, it can return negative values.

You must not have any logic that works with GetHashCode() values.
GetHashCode() is not guaranteed to be unique and can change between builds.

GetHashCode() must be treated as an opaque token that can be combined with other hashes or modded out into hashtables.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    SLaks is right - particularly between 32-bit and 64-bit architectures. – Chris Barlow Jan 31 '12 at 18:18
  • 1
    wow, it changes between builds, that sucks, I have to use something else, thanks anyway :) – Eric Yin Jan 31 '12 at 18:19
  • 2
    Yes; you _must_ use something else. `GetHashCode()` is only for in-memory hashtables. You should probably use SHA512. – SLaks Jan 31 '12 at 18:19
  • @Barlow, so if I constant build on x64, the value won't change, right? How about x128, eventually we will have – Eric Yin Jan 31 '12 at 18:21
  • 5
    @EricYin: **DO NOT DO THIS**! See http://blogs.msdn.com/b/ericlippert/archive/2005/10/24/do-not-use-string-hashes-for-security-purposes.aspx – SLaks Jan 31 '12 at 18:22
  • @Slaks, sure, I will stick to my SHA512, its very easy and fast in .NET anyway – Eric Yin Jan 31 '12 at 18:22
  • @SLaks what if I just want to have a seed for my Random generator. I just cannot use Guid.NewGuid().GetHashCode(); ? – Teoman shipahi Jun 08 '17 at 20:51
  • @Teomanshipahi: If you don't care about security or predictability, anything is fine. If this is at all related to crypto, you must use a secure PRNG. – SLaks Jun 08 '17 at 20:54
  • 2
    Updated working URL to Eric Lippert's blog post: https://blogs.msdn.microsoft.com/ericlippert/2005/10/24/do-not-use-string-hashes-for-security-purposes/ – Raj Rao Apr 07 '20 at 14:20
7

It can return negative value (based on msdn):
http://msdn.microsoft.com/en-us/library/system.string.gethashcode.aspx

cichy
  • 10,464
  • 4
  • 26
  • 36