steve
steve

Reputation: 57

Check if object exists at list index in Visual Basic

I need to check if an object exists at a specified index in a List in Visual Basic. What I have is

Dim theList As New List(Of Integer)({1,2,3})
If theList.Item(3) = Nothing Then
    'some code to execute if there is nothing at position 3 in the list

But when I run the program I get System.ArgumentOutOfRangeException, saying the index is out of range. Of course it is, the entire point was to see if it does or doesn't exist. If "= Nothing" is not the way to check if something exists at that index, what is?

I am in my Application Development class and we are working on Windows Forms Applications using Visual Studio 2017, if any of that matters.

Upvotes: 2

Views: 3620

Answers (2)

Blackwood
Blackwood

Reputation: 4534

If you are checking a list of objects, you need to change two things.

  1. The way to check for nothing is to use Is Nothing.
  2. You can't even attempt to check items beyond the end of the list, so you must first check that the index you want to use is less than the number of items in the list'

You should change your code to

If theList.Items.Count > 3 AndAlso theList.Item(3) Is Nothing Then
    'some code to execute if there is nothing at position 3 in the list
End If

Note the use of AndAlso rather than And in the If statement. This is required because it ensures that the check on item 3 happens only if there are at least 4 items in the list.

Also note that, in the code you posted, the list is a List(Of Integer). An Integer can never be Nothing, so the second part of you check is either not needed or you should be checking for = 0 instead of Is Nothing.

Upvotes: 4

dbasnett
dbasnett

Reputation: 11773

Any time you have a list you can only access members of the list, accessing an imaginary item outside of the bounds will result in the error you specified.. The integer datatype comparison to Nothing is a comparison to 0. IMO this use of nothing is not ideal. If you want nothing you might look at Nullable. Here is some code to take a look at.

    Dim theList As New List(Of Integer)({0, 1, 2, 3})

    For idx As Integer = 0 To theList.Count - 1 'look at each item
        If theList.Item(idx) = Nothing Then
            Stop ' item is 0
        End If
    Next

    Dim i As Integer = Nothing ' i = 0

    'Dim theListN As New List(Of Integer?)({1, 2, 3, Nothing, 5})
    Dim theListN As New List(Of Nullable(Of Integer))({1, 2, 3, Nothing, 5, Nothing})
    For idx As Integer = 0 To theListN.Count - 1 'look at each item
        If theListN.Item(idx) Is Nothing Then
            'item is nothing, not 0
            Dim nullI As Nullable(Of Integer) = theListN.Item(idx)
            If Not nullI.HasValue Then Stop
        End If
    Next

Upvotes: 1

Related Questions