Will string.GetHashCode() return negative value?
Asked Answered
K

2

19

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

Kapor answered 31/1, 2012 at 18:14 Comment(7)
FYI, GetHashCode is part of .NET, not part of C#Dignity
Looking at the logic via Reflector, I would say so.Monotint
blogs.msdn.com/b/ericlippert/archive/2011/02/28/…Trussing
blogs.msdn.com/b/ericlippert/archive/2005/10/24/…Trussing
vkreynin.wordpress.com/2008/07/05/explaining-gethashcode-method check this :)Caltrop
You probably would have seen negative results when sampling string of (strongly) varying lengths.Vanthe
You chose an atypical batch of "random" strings then.Weller
T
31

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.

Trussing answered 31/1, 2012 at 18:16 Comment(9)
SLaks is right - particularly between 32-bit and 64-bit architectures.Miriam
wow, it changes between builds, that sucks, I have to use something else, thanks anyway :)Kapor
Yes; you must use something else. GetHashCode() is only for in-memory hashtables. You should probably use SHA512.Trussing
@Barlow, so if I constant build on x64, the value won't change, right? How about x128, eventually we will haveKapor
@EricYin: DO NOT DO THIS! See blogs.msdn.com/b/ericlippert/archive/2005/10/24/…Trussing
@Slaks, sure, I will stick to my SHA512, its very easy and fast in .NET anywayKapor
@Trussing what if I just want to have a seed for my Random generator. I just cannot use Guid.NewGuid().GetHashCode(); ?Bust
@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.Trussing
Updated working URL to Eric Lippert's blog post: blogs.msdn.microsoft.com/ericlippert/2005/10/24/…Westhead
L
7

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

Lobation answered 31/1, 2012 at 18:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.