Search code examples
.netvb.netdelegates.net-2.0predicate

VB.NET inline delegate predicate not working


This is my problem. If I write this -

Private ListValue As Object = Nothing

Private Sub FindIndex(ByVal e As ListBoxFindItemArgs)
    e.IsFound = Object.Equals(ListValue, e.ItemValue)
End Sub

Private Sub SearchValues
    ListValue  = 5
    Index = Me.lst_department.FindItem(0, True, AddressOf FindIndex)
End Sub

But I'm just out of my wit why this code, written to do the same thing is not working -

Private Sub SearchValues
    ListValue  = 5
    Index = Me.lst_department.FindItem(0, True, Function(e As ListBoxFindItemArgs) e.IsFound = Object.Equals(ListValue, e.ItemValue))
End Sub

Solution

  • Because your “predicate” is not a function1, it’s a Sub. If you are using the most recent version of VB, you can write the following; otherwise, you’re out of luck:

    Index = Me.lst_department.FindItem(0, True, Sub(e As ListBoxFindItemArgs) e.IsFound = Object.Equals(ListValue, e.ItemValue))
    

    1 Furthermore, it’s not a predicate. A predicate is a specific type of function having the signature Function(x As T) As Boolean for some type T.