Should the hash code of null always be zero, in .NET

前端 未结 9 2314
梦谈多话
梦谈多话 2020-12-13 16:57

Given that collections like System.Collections.Generic.HashSet<> accept null as a set member, one can ask what the hash code of null

9条回答
  •  我在风中等你
    2020-12-13 17:15

    But is there any reason why the hash code of null should be 0?

    It could have been anything at all. I tend to agree that 0 wasn't necessarily the best choice, but it's one that probably leads to fewest bugs.

    A hash function absolutely must return the same hash for the same value. Once there exists a component that does this, this is really the only valid value for the hash of null. If there were a constant for this, like, hm, object.HashOfNull, then someone implementing an IEqualityComparer would have to know to use that value. If they don't think about it, the chance they'll use 0 is slightly higher than every other value, I reckon.

    at least for HashSet<>, it is not even possible to change the hash of null

    As mentioned above, I think it's completely impossible full stop, just because there exist types which already follow the convention that hash of null is 0.

提交回复
热议问题