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

前端 未结 9 2316
梦谈多话
梦谈多话 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题