Home > Mobile >  Intellisense not showing the .Length, .Count methods
Intellisense not showing the .Length, .Count methods

Time:11-04

How can I check if item is null?

Dim list As New List(Of ContactU)
list = resource.ContactUs.ToList()
If list.Count <> 0 Then
    For Each item In list
        If item Then
            'Do the loop 
        End If
    Next
End If

CodePudding user response:

Your question title conflicts with your written question of "How can I check if item is null?" To answer that question, you check if the variable Is Nothing:

Dim list As List(Of ContactU) = resource.ContactUs.ToList()

If list Is Nothing Then
    ' Handle what happens when the list is Null/Nothing.
Else
    ' Handle what happens when the list is not Null/Nothing.
End If

When checking if a variable is not Null/Nothing, the keyword is as follows (IsNot being one keyword):

If list IsNot Nothing Then

If you want to check that a variable IsNot Nothing and in the same statement check a property of the variable, you have to use the short-circuiting version of And or Or:

If list IsNot Nothing AndAlso list.Count > 0 Then

This way, if list is Nothing, the list.Count will not get evaluated, and will not throw a null reference exception.

  • Related