Is .GetHashCode guaranteed to be the same across systems/platform versions? [duplicate]

你离开我真会死。 提交于 2019-12-02 13:28:54

No. Other questions? :-)

The algorithms used aren't published nor they are in the Ecma standard.

I'll quote from the MSDN String.GetHashCode (I think that this example is good enough)

The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another. A reason why this might happen is to improve the performance of GetHashCode.

Technically, it depends on how your classes override GetHashCode. If you have this:

class MyClass
{
    public override int GetHashCode() { return 42; }
}

then that would be consistent in Mono and .NET. :)

Of course if your GetHashCode implementation depends on types that do not guarantee consistency across platforms (e.g. string), then MyClass.GetHashCode() will also not be consistent.

Ekk

The answer is No

Rule: Consumers of GetHashCode cannot rely upon it being stable over time or across appdomains

Suppose you have a Customer object that has a bunch of fields like Name, Address, and so on. If you make two such objects with exactly the same data in two different processes, they do not have to return the same hash code. If you make such an object on Tuesday in one process, shut it down, and run the program again on Wednesday, the hash codes can be different./blockquote>

Read full article from Guidelines and rules for GetHashCode

You could make return the same thing if you override GetHashCode() and provide your own implementation. Although I'm unsure why you would want to use the return from that as a key to persistent storage, it is just as easy to give your objects their own predetermined (calculated) key when they are first inserted into the repository. All due respect, but using the returned hash code as the key just seems like you are trying to be too clever for your own good.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!