20

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

7

2 Answers 2

32

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.

Sign up to request clarification or add additional context in comments.

9 Comments

SLaks is right - particularly between 32-bit and 64-bit architectures.
wow, it changes between builds, that sucks, I have to use something else, thanks anyway :)
Yes; you must use something else. GetHashCode() is only for in-memory hashtables. You should probably use SHA512.
Updated working URL to Eric Lippert's blog post: blogs.msdn.microsoft.com/ericlippert/2005/10/24/…
|
8

It can return a negative value (based on MSDN):
https://learn.microsoft.com/dotnet/api/system.string.gethashcode

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.