0

I'm going to have to move away from the Find(), .FirstOrDefault() etc. and replace it with loops unless someone can explain how to deal with lists that will not return a value?

Public Class Form1

    Public Class TestClass
        Public Property item1 As String
        Public Property item2 As String
    End Class

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim myLst As New List(Of TestClass)
        myLst.Add(New TestClass With {.item1 = "A", .item2 = "B"})
        myLst.Add(New TestClass With {.item1 = "C", .item2 = "D"})

        Debug.WriteLine(myLst.Find(Function(n) n.item1 = "X").item1) ' nullreferenceexception, what?

    End Sub

End Class
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Rose
  • 641
  • 7
  • 17

1 Answers1

5

You just need to handle the case where Find or FirstOrDefault returns nothing. You are accessing the item1 property if nothing is returned, which causes the NullReferenceException.

Public Sub Button2_Click(sender As Object, e As EventArgs)
    Dim myLst As New List(Of TestClass)
    myLst.Add(New TestClass With {.item1 = "A", .item2 = "B"})
    myLst.Add(New TestClass With {.item1 = "C", .item2 = "D"})

    Dim tryFindItem = myLst.Find(Function(n) n.item1 = "X")
    If tryFindItem IsNot Nothing Then
        Debug.WriteLine(tryFindItem.item1)
    Else
        Debug.WriteLine("Nothing was found!")
    End If
End Sub
vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • Thanks for the example, it works perfect. It also really helped me understand some basics about this stuff, please down vote me on this question. – Rose Dec 31 '14 at 19:29
  • 1
    It's not a bad question. The question is 1) clear, concise and 2) offers a [SSCCE](http://sscce.org/), which are all elements of a good question. Whether or not the question is easy or hard makes no bearing to me if the question is good or not since that all depends on experience and background. – vcsjones Dec 31 '14 at 19:34