[vb.net] Null check in VB

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

This question is related to vb.net null runtime-error

The answer is


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.


Your code is way more cluttered than necessary.

Replace (Not (X Is Nothing)) with X IsNot Nothing and omit the outer parentheses:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For i As Integer = 0 To comp.Container.Components.Count() - 1
        fixUIIn(comp.Container.Components(i), style)
    Next
End If

Much more readable. … Also notice that I’ve removed the redundant Step 1 and the probably redundant .Item.

But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each instead:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For Each component In comp.Container.Components
        fixUIIn(component, style)
    Next
End If

Examples related to vb.net

How to get parameter value for date/time column from empty MaskedTextBox HTTP 415 unsupported media type error when calling Web API 2 endpoint variable is not declared it may be inaccessible due to its protection level Differences Between vbLf, vbCrLf & vbCr Constants Simple working Example of json.net in VB.net How to open up a form from another form in VB.NET? Delete a row in DataGridView Control in VB.NET How to get cell value from DataGridView in VB.Net? Set default format of datetimepicker as dd-MM-yyyy How to configure SMTP settings in web.config

Examples related to null

getElementById in React Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? How to resolve TypeError: Cannot convert undefined or null to object Check if returned value is not null and if so assign it, in one line, with one method call How do I assign a null value to a variable in PowerShell? Using COALESCE to handle NULL values in PostgreSQL How to check a Long for null in java Check if AJAX response data is empty/blank/null/undefined/0 Best way to check for "empty or null value"

Examples related to runtime-error

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined' what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? javac: invalid target release: 1.8 C++ error : terminate called after throwing an instance of 'std::bad_alloc' Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error No Main class found in NetBeans Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0 TypeError: Cannot read property "0" from undefined Array Index Out of Bounds Exception (Java) Excel VBA Automation Error: The object invoked has disconnected from its clients