Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetHashCode on null fields?

Tags:

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 
like image 273
Shimmy Weitzhandler Avatar asked Mar 15 '10 02:03

Shimmy Weitzhandler


People also ask

Do I need to implement GetHashCode?

Yes, it is important if your item will be used as a key in a dictionary, or HashSet<T> , etc - since this is used (in the absence of a custom IEqualityComparer<T> ) to group items into buckets. If the hash-code for two items does not match, they may never be considered equal (Equals will simply never be called).

What is the purpose of GetHashCode?

The GetHashCode method provides this hash code for algorithms that need quick checks of object equality. For information about how hash codes are used in hash tables and for some additional hash code algorithms, see the Hash Function entry in Wikipedia. Two objects that are equal return hash codes that are equal.

Why do we need GetHashCode C#?

GetHashCode returns a value based on the current instance that is suited for hashing algorithms and data structures such as a hash table. Two objects that are the same type and are equal must return the same hash code to ensure that instances of System.

Is GetHashCode unique C#?

NO! A hash code is not an id, and it doesn't return a unique value. This is kind of obvious, when you think about it: GetHashCode returns an Int32 , which has “only” about 4.2 billion possible values, and there's potentially an infinity of different objects, so some of them are bound to have the same hash code.


1 Answers

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)

like image 162
itowlson Avatar answered Sep 25 '22 01:09

itowlson