Do I need to override GetHashCode() on reference types?

不想你离开。 提交于 2019-11-30 17:14:06

You only need to override GetHashCode() on reference types if you override Object.Equals().

The reason for this is simple - normally, 2 references will always be distinct (a.Equals(b)==false, unless they're the same object). The default implementation of GetHashCode() will provide 2 distinct hashes in this case, so all is good.

If you override Equals(), though, this behavior is not guaranteed. If two objects are equal (as per Equals()), you need to guarantee that they'll have the same hash code with GetHashCode, so you should override it.

I just did a sample test, and I do not see how it starts at 1 and gets increment.

for (int i = 0; i < 16; i++)
{
    object obj = new object();
    Console.Write(obj.GetHashCode() + " ");
}

with these results:

45653674 41149443 39785641 45523402 35287174 44419000 52697953 22597652 
10261382 59109011 42659827 40644060 17043416 28756230 18961937 47980820

In fact, using Reflector, I only could see this:

internal static extern int InternalGetHashCode(object obj);

So how it really happens is a mistery to me (there might be a pattern, but I am not going to dig deeper at this point -- maybe some sort of "pseudo random number" algorithm?). Somebody from the CLR team could answer that.

As for the other questions, Reed actually beat me to the punch re: GetHashCode and Equals. The MSDN page describes it with few more gory details, just in case.

Paul Westcott

Have a look at the comment I left on the article: GetHashCode Extension Method

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