I have some rather straightforward code for a Compare Function
Public Overridable Function Comparer(thisValue As Object, otherValue As Object) As Integer
Try
If thisValue Is Nothing Then
If otherValue Is Nothing Then
Return 0
Else
Return -1
End If
Else
If otherValue Is Nothing Then
Return 1
Else
Return thisValue.ToString.CompareTo(otherValue.ToString)
End If
End If
Catch ex As Exception
Return 0
End Try
End Function
The reason for the try-catch block is: I get a NullReferenceException at the actual comparision line if thisValue is Nothing. The debugger shows me that thisValue is "Nothing" but lands in the ELSE branch anyway.
Can anyone tell me why?
UPDATE: I have tried to amend the situation by inserting yet another check for Nothing. In my scenario this boils down to a few hundred Exceptions and the execution speed is bearable. Don't want to imagine someone trying to sort an empty column though.
https://i.sstatic.net/8dnXD.png
How is this possible? Is there another "LEVEL" of Nothingness that i don't know about. Do i need to check the type of thisValue and otherValue?
The Function is never overridden. I have tried removing the "Overridable" to no effect.
Perhaps it isn't that thisValue
is Nothing
, it is the fact that .ToString()
is returning Nothing? Try this code to test it out:
Public Overridable Function Comparer(thisValue As Object, otherValue As Object) As Integer
Try
If thisValue Is Nothing Then
If otherValue Is Nothing Then
Return 0
Else
Return -1
End If
Else
If otherValue Is Nothing Then
Return 1
Else
Dim thisValueStr As String = thisValue.ToString()
Dim otherValueStr As String = otherValue.ToString()
'HERE, CHECK THE TWO STRINGS FOR NULL!!!
Return thisValueStr .CompareTo(otherValueStr )
End If
End If
Catch ex As Exception
Return 0
End Try
End Function
If this is the case, double-check the implementation of ToString()
in the object being passed (assuming it is a custom type).