I have a custom class which uses generics.
I need to use this class as the key of a dictionary as shown in the code example below:
I am able to hit the overridden Object.GetHashCode
method, but i'm not sure how to proceed from there. Please help, Thanks.
Module Module2
Dim myStore As New Dictionary(Of Pair(Of Long, Integer), String)
Public Function ContainsItem(id As Long, code As Integer) As Boolean
Return myStore.ContainsKey(New Pair(Of Long, Integer)(id, code))
End Function
Public Class Pair(Of T1, T2)
Implements IEquatable(Of Pair(Of T1, T2))
Private v1 As T1
Private v2 As T2
Public Sub New(ByVal v1 As T1, ByVal v2 As T2)
Me.v1 = v1
Me.v2 = v2
End Sub
Public Function first() As T1
Return v1
End Function
Public Function second() As T2
Return v2
End Function
Public Overrides Function GetHashCode() As Integer
'i hit this break point, but ...
'how do i compute an integer hashcode from a long and an Integer?
Return MyBase.GetHashCode()
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Return MyBase.Equals(obj)
End Function
Public Function Equals1(other As Pair(Of T1, T2)) As Boolean Implements IEquatable(Of Pair(Of T1, T2)).Equals
'just as a test, but the code never gets here.
Return True
End Function
End Class
Public Sub TestCase()
Dim a = New Pair(Of Long, Integer)(10, 10)
myStore.Add(a, "Item 1")
Dim b = ContainsItem(10, 10)
'b is always false
End Sub
End Module
This implements
IEquatable
and overridesGetHashCode
andEquals
:Then, the methods:
Testing:
Result:
The tests using
c
are actually false. The object 'c' was never added to the Dictionary, and 'c' is a different object thana
. But the overrides used simply tests the objects based on the 2 values which are the same.I do not think I would do this, because
a<>c
. Instead, maybe use a collection class of some sort and avoid redefiningEquals
. The exact implementation would depend on whats in the collection. This would be a last resort, for me.See Also: