I have a list of custom object types say
Dim a As New List(Of CustomType)
populated with instances. I have a comparer class that inherits
Public Class CustomTypeComparer
Implements IComparer(Of CustomType)
Public Function Compare(x As CustomType, y As CustomType) As Integer Implements IComparer(Of CustomType).Compare
...
End Function
End Class
that is called using the
a.Sort(New CustomTypeComparer)
method. The comparer's only method Compare()
is called automatically, however occasionally the method fails because x
is undefined or 'Not set to an instance of an object'.
I have scoured the list being sorted to check none of the elements are Nothing, confirmed with a watch on a.Contains(Nothing)
which returns False
and checked using other comparers that look at other parts of the object, none of those have problems with the list, only this one.
How can I study the problem any deeper? Is there any insight people can give on this issue?
Update:
Reading the reference source code of the framework, the list sort method uses the underlying Array.Sort()
method. Taking a hint from that and I tried using the List.TrimExcess()
method on the list, this has changed the behaviour and no Nothing
s are passed to the IComparer. A commenter discovered that IComparers are expected to compare nulls, which combines with the Array's underlying bound being greater than the array and silently having Nothing
s in it to generate expected functionality.