I want to use a Dictionary(Of Key, Value), and the Key is not a base type, but a class like:
Public Class MyKey
Sub New(ByVal packet As String, ByVal sent As Boolean)
Me.packet = packet.ToUpper.Trim
Me.sent = sent
End Sub
Private packet As String
Private sent As Boolean
End Class
Now to have the Dictionary work and find the keys, I have to implement the System.IEquatable interface in the Key class (or use a different constructor, but that's another story):
Public Class MyKey
Implements System.IEquatable(Of MyKey)
Sub New(ByVal packet As String, ByVal sent As Boolean)
Me.packet = packet.ToUpper.Trim
Me.sent = sent
End Sub
Public Overloads Function Equals(ByVal other As MyKey) As Boolean Implements IEquatable(Of MyKey).Equals
Return other.sent = Me.sent AndAlso other.packet = Me.packet
End Function
Private packet As String
Private sent As Boolean
End Class
But to have consistent results I have also to implement Object.Equals and Object.GetHashCode:
Public Class MyKey
Implements System.IEquatable(Of MyKey)
Sub New(ByVal packet As String, ByVal sent As Boolean)
Me.packet = packet.ToUpper.Trim
Me.sent = sent
End Sub
Public Overloads Function Equals(ByVal other As ChiavePietanza) As Boolean Implements IEquatable(Of MyKey).Equals
Return other.sent = Me.sent AndAlso other.packet = Me.packet
End Function
Overrides Function Equals(ByVal o As Object) As Boolean
Dim cast As MyKey = DirectCast(o, MyKey)
Return Equals(cast)
End Function
Public Overrides Function GetHashCode() As Integer
Return packet.GetHashCode Or sent.GetHashCode
End Function
Private packet As String
Private sent As Boolean
End Class
The question is: is that GetHashCode implementation correct? How should I implement it, to return a hashcode that kind of merges the string and the boolean hash codes?