Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make .NET Core GetHashCode deterministic

Tags:

.net-core

I just wasted few hours of debugging before realizing that contrary to .NET, in .NET Core, GetHashCode returns a different value every time you run your code. I totally understand the rationale for this. Relying on hash code values is a very bad idea (like serializing them). I even remember that internal builds of .NET at Microsoft (prior to Core) would change the behavior of GetHashCode for every build so that nobody gets too comfortable with it.

Having said all this, I’m currently debugging complex code that makes heavy use of GetHashCode. I know the bug is my own doing and has nothing to do with GetHashCode but each time I run it, it fails elsewhere. Very annoying. Is there a way to force GetHashCode to behave like in .NET (while I’m debugging) without having to write my own hash function and having to replace it everywhere in my code?

like image 217
Franck Jeannin Avatar asked Dec 16 '16 11:12

Franck Jeannin


People also ask

Is string GetHashCode deterministic?

The key point is that the hash codes are deterministic for a given program execution, that means the only time it'll be an issue is if you're saving the hash code outside of a process, and loading it into another one.

Is string GetHashCode unique?

If two string objects are equal, the GetHashCode method returns identical values. However, there is not a unique hash code value for each unique string value. Different strings can return the same hash code. The hash code itself is not guaranteed to be stable.

Can GetHashCode be negative?

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.

What is the return type of the string GetHashCode () in C#?

Syntax: public override int GetHashCode (); Return Value: The return type of this method is System.


1 Answers

According to docs only change of framework should change the hash result. I too stumbled upon this. My solution was to create my own hash algorithm. It just took a few minutes as I didn't need anything fancy.

private static int GetSimpleHash(string s)
{
    return s.Select(a => (int)a).Sum();
}

On a side note I have filed a bug for dotnet core 1.1. (string).GetHashCode() here.

Update

The hash can change due to framework or domain. This means that two subsequent runs of the same program can return different results.
Alas my bug report is moot and changed to a documentation update instead.

Update update

Documentation is updated to be a little bit more clear.

like image 194
LosManos Avatar answered Jun 03 '23 04:06

LosManos