Home > Back-end >  Will I get NullReferenceException [closed]
Will I get NullReferenceException [closed]

Time:09-24

I am researching code and I have very limited knowledge of VB.net

Hotel is a class and Hotel.City is Null and so, if I run the below code will I get NullReferenceException. Can anyone help also a small code will be helpful.

If hotel.City IsNot Nothing AndAlso Not String.IsNullOrEmpty(hotel.City.Code) Then
    Dim cityCode As String = hotel.City.Code
                
End If

CodePudding user response:

The code you posted can still produce NullReferenceException if the hotel variable itself is Nothing.

However, if you can know this will not be the case, the AndAlso logical operator will short circuit and stop the second test from running, so the exception will be avoided.

This is different from the older And operator, which would not short circuit. With the older operator, both tests would always run, you would still get the exception, and you have to nest an additional If conditional expression to avoid it.

CodePudding user response:

You are checking if an element of a null class is null or empty. I don't remember VB well, try this:

    If hotel.City IsNot Nothing AndAlso Not String.IsNullOrEmpty(hotel?.City?.Code) Then
      Dim cityCode As String = hotel.City.Code
    End If
  • Related