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

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

    Personally I find using nullable values a bit awkward and try to avoid them whenever I can. Your issue is just another reason. Sometimes they are very handy though but my rule of thumb is not to mix value types with null if possible simply because these are from two different worlds. In .NET framework they seem to do the same - a lot of value types provide TryParse method which is a way of separating values from no value (null).

    In your particular case it is easy to get rid of the problem because you handle your own Season type.

    (Season?)null to me means 'season is not specified' like when you have a webform where some fields are not required. In my opinion it is better to specify that special 'value' in the enum itself rather than use a bit clunky Nullable. It will be faster (no boxing) easier to read (Season.NotSpecified vs null) and will solve your problem with hash codes.

    Of course for other types, like int you can't expand value domain and to denominate one of the values as special is not always possible. But with int? hash code collision is much smaller problem, if at all.

提交回复
热议问题