Null check in VB

Ben Leggiero picture Ben Leggiero · Apr 7, 2011 · Viewed 245.6k times · Source

All I want to do is check if an object is null, but no matter what I do, if it compiles, it throws a NullReferenceException just trying to check! Here's what I've done:

    If ((Not (comp.Container Is Nothing)) And (Not (comp.Container.Components Is Nothing))) Then
        For i As Integer = 0 To comp.Container.Components.Count() - 1 Step 1
            fixUIIn(comp.Container.Components.Item(i), style)
        Next
    End If

    If ((Not IsDBNull(comp.Container)) And (Not IsDBNull(comp.Container.Components))) Then
        For i As Integer = 0 To comp.Container.Components.Count() - 1 Step 1
            fixUIIn(comp.Container.Components.Item(i), style)
        Next
    End If

    If ((Not IsNothing(comp.Container)) And (Not IsNothing(comp.Container.Components))) Then
        For i As Integer = 0 To comp.Container.Components.Count() - 1 Step 1
            fixUIIn(comp.Container.Components.Item(i), style)
        Next
    End If

    If ((Not (comp.Container Is DBNull.Value)) And (Not (comp.Container.Components Is DBNull.Value))) Then
        For i As Integer = 0 To comp.Container.Components.Count() Step 1
            fixUIIn(comp.Container.Components.Item(i), style)
        Next
    End If

I've looked through VB books, searched several forums, and everything that SHOULD work doesn't! Sorry for asking such a remedial question, but I just need to know.

Just so you know, the debugger says that the null object is comp.Container

Answer

Ken Pespisa picture Ken Pespisa · Apr 7, 2011

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.