Reputation: 5617
I'm trying to test if an object is nothing before I get it's value, but I get an error "NullReferenceException"
happens on the first line here:
If Not ORInvoiceLineRet.InvoiceLineRet.ItemRef.FullName Is Nothing Then
li.FullName = ORInvoiceLineRet.InvoiceLineRet.ItemRef.FullName.GetValue()
End If
System.NullReferenceException {"Object reference not set to an instance of an object."}
How can I test for this, without just handling the error in a try/catch?
Upvotes: 2
Views: 232
Reputation: 460098
There are more objects involved that can be nothing:
ORInvoiceLineRet
can be nothingORInvoiceLineRet.InvoiceLineRet
can be nothingORInvoiceLineRet.InvoiceLineRet.ItemRef
can be nothingORInvoiceLineRet.InvoiceLineRet.ItemRef.FullName
can be nothingSo the only safe way here is:
If ORInvoiceLineRet IsNot Nothing _
AndAlso ORInvoiceLineRet.InvoiceLineRet IsNot Nothing _
AndAlso ORInvoiceLineRet.InvoiceLineRet.ItemRef IsNot Nothing _
AndAlso ORInvoiceLineRet.InvoiceLineRet.ItemRef.FullName IsNot Nothing Then
li.FullName = ORInvoiceLineRet.InvoiceLineRet.ItemRef.FullName.GetValue()
End If
Upvotes: 7
Reputation: 35716
Either ORInvoiceLineRet.InvoiceLineRet.ItemRef
is Nothing
, ORInvoiceLineRet.InvoiceLineRet
is Nothing
or ORInvoiceLineRet
is Nothing
.
Its hard to access the properties of Nothing
so a NullReferenceException
is thrown.
You could test the chain all in one go using OrElse
If Not (ORInvoiceLineRet Is Nothing OrElse _
ORInvoiceLineRet.InvoiceLineRet Is Nothing OrElse _
ORInvoiceLineRet.InvoiceLineRet.ItemRef Is Nothing OrElse _
ORInvoiceLineRet.InvoiceLineRet.ItemRef.FullName Is Nothing)
End If
If the left expression evaluates to True
, OrElse
will not evaluate the right.
Upvotes: 2