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

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

    Good question.

    I just tried to code this:

    enum Season
    {
      Spring,
      Summer,
      Autumn,
      Winter,
    }
    

    and execute this like this:

    Season? v = null;
    Console.WriteLine(v);
    

    it returns null

    if I do, instead normal

    Season? v = Season.Spring;
    Console.WriteLine((int)v);
    

    it return 0, as expected, or simple Spring if we avoid casting to int.

    So.. if you do the following:

    Season? v = Season.Spring;  
    Season? vnull = null;   
    if(vnull == v) // never TRUE
    

    EDIT

    From MSDN

    If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values

    In other words: if two objects have same hash code that doesn't mean that they are equal, cause real equality is determined by Equals.

    From MSDN again:

    The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.

提交回复
热议问题