views:

213

answers:

1

How do I deal with null fields in GetHashCode function?

Module Module1
  Sub Main()
    Dim c As New Contact
    Dim hash = c.GetHashCode
  End Sub

  Public Class Contact : Implements IEquatable(Of Contact)
    Public Name As String
    Public Address As String

    Public Overloads Function Equals(ByVal other As Contact) As Boolean _
        Implements System.IEquatable(Of Contact).Equals
      Return Name = other.Name AndAlso Address = other.Address
    End Function

    Public Overrides Function Equals(ByVal obj As Object) As Boolean
      If ReferenceEquals(Me, obj) Then Return True

      If TypeOf obj Is Contact Then
        Return Equals(DirectCast(obj, Contact))
      Else
        Return False
      End If
    End Function

    Public Overrides Function GetHashCode() As Integer
      Return Name.GetHashCode Xor Address.GetHashCode
    End Function
  End Class
End Module
+1  A: 

Typically, you check for null and use 0 for that "part" of the hash code if the field is null:

return (Name == null ? 0 : Name.GetHashCode()) ^ 
  (Address == null ? 0 : Address.GetHashCode());

(pardon the C#-ism, not sure of the null check equivalent in VB)

itowlson
np about the 'csism'. you just clarified that the hash code for null is 0.
Shimmy
btw, if the distinguishing field is an int, can I return the int itself instead of it's hashcode? would that be a bad idea?i.e. return ContactId ^ (Name == null ? 0 : Name.GetHashCode) (it's an int)?
Shimmy
The only requirement for hash codes is that equal objects return equal hash codes. Since equal ints are equal, returning the int as its own hash code is fine. Indeed, this is exactly what Int32.GetHashCode appears to do...!
itowlson
@itowlson, thanks, i thought so but wasn't sure, thanks a lot!!
Shimmy