GetHashCode on null fields?

前端 未结 2 1663
离开以前
离开以前 2021-02-07 03:30

How do I deal with null fields in GetHashCode function?

Module Module1
  Sub Main()
    Dim c As New Contact
         


        
2条回答
  •  灰色年华
    2021-02-07 03:52

    As Jeff Yates suggested, the override in the answer would give the same hash for (name = null, address = "foo") as (name = "foo", address = null). These need to be different. As suggested in link, something similar to the following would be better.

    public override int GetHashCode()
    {
        unchecked // Overflow is fine, just wrap
        {
            int hash = 17;
            hash = hash * 23 + (Name == null ? 0 : Name.GetHashCode());
            hash = hash * 23 + (Address == null ? 0 : Address.GetHashCode());
        }
        return hash;
    }
    

    What is the best algorithm for an overridden System.Object.GetHashCode?

提交回复
热议问题