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

前端 未结 9 2322
梦谈多话
梦谈多话 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:22

    So long as the hash code returned for nulls is consistent for the type, you should be fine. The only requirement for a hash code is that two objects that are considered equal share the same hash code.

    Returning 0 or -1 for null, so long as you choose one and return it all the time, will work. Obviously, non-null hash codes should not return whatever value you use for null.

    Similar questions:

    GetHashCode on null fields?

    What should GetHashCode return when object's identifier is null?

    The "Remarks" of this MSDN entry goes into more detail around the hash code. Poignantly, the documentation does not provide any coverage or discussion of null values at all - not even in the community content.

    To address your issue with the enum, either re-implement the hash code to return non-zero, add a default "unknown" enum entry equivalent to null, or simply don't use nullable enums.

    Interesting find, by the way.

    Another problem I see with this generally is that the hash code cannot represent a 4 byte or larger type that is nullable without at least one collision (more as the type size increases). For example, the hash code of an int is just the int, so it uses the full int range. What value in that range do you choose for null? Whatever one you pick will collide with the value's hash code itself.

    Collisions in and of themselves are not necessarily a problem, but you need to know they are there. Hash codes are only used in some circumstances. As stated in the docs on MSDN, hash codes are not guaranteed to return different values for different objects so shouldn't be expected to.

提交回复
热议问题