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
Change your And
s to AndAlso
s
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