ChatGPT
ChatGPT

Reputation: 5617

null reference not evaluating to nothing

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

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460098

There are more objects involved that can be nothing:

  • ORInvoiceLineRet can be nothing
  • ORInvoiceLineRet.InvoiceLineRet can be nothing
  • ORInvoiceLineRet.InvoiceLineRet.ItemRef can be nothing
  • ORInvoiceLineRet.InvoiceLineRet.ItemRef.FullName can be nothing

So 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

Jodrell
Jodrell

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

Related Questions