So I\'m trying to figure out how to correctly override GetHashCode() in VB for a large number of custom objects. A bit of searching leads me to this wonderful
Use Long to avoid the overflow:
Dim hash As Long = 17
'' etc..
Return CInt(hash And &H7fffffffL)
The And operator ensures no overflow exception is thrown. This however does lose one bit of "precision" in the computed hash code, the result is always positive. VB.NET has no built-in function to avoid it, but you can use a trick:
Imports System.Runtime.InteropServices
Module NoOverflows
Public Function LongToInteger(ByVal value As Long) As Integer
Dim cast As Caster
cast.LongValue = value
Return cast.IntValue
End Function
_
Private Structure Caster
Public LongValue As Long
Public IntValue As Integer
End Structure
End Module
Now you can write:
Dim hash As Long = 17
'' etc..
Return NoOverflows.LongToInteger(hash)