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

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

    So this could be avoided by using an Unknown enum value (although it seems a bit weird for a Season to be unknown). So something like this would negate this issue:

    public enum Season
    {
       Unknown = 0,
       Spring,
       Summer,
       Autumn,
       Winter
    }
    
    Season some_season = Season.Unknown;
    int code = some_season.GetHashCode(); // 0
    some_season = Season.Autumn;
    code = some_season.GetHashCode(); // 3
    

    Then you would have unique hash code values for each season.

    0 讨论(0)
  • 2020-12-13 17:30
    Tuple.Create( (object) null! ).GetHashCode() // 0
    Tuple.Create( 0 ).GetHashCode() // 0
    Tuple.Create( 1 ).GetHashCode() // 1
    Tuple.Create( 2 ).GetHashCode() // 2
    
    0 讨论(0)
  • 2020-12-13 17:36

    It is 0 for the sake of simplicity. There is no such hard requirement. You only need to ensure the general requirements of hash coding.

    For example, you need to make sure that if two objects are equal, their hashcodes must always be equal too. Therefore, different hashcodes must always represent different objects (but it's not necessarily true vice versa: two different objects may have the same hashcode, even though if this happens often then this is not a good quality hash function -- it doesn't have a good collision resistance).

    Of course, I restricted my answer to requirements of mathematical nature. There are .NET-specific, technical conditions as well, which you can read here. 0 for a null value is not among them.

    0 讨论(0)
提交回复
热议问题