0

I want to know if there is a simple and clean way, like a method of sorts, of accesing an object property of a certain object even touhg this property could be null, that, in consecuence, this may throw a null pointer exception, and, if it is null, then do some other thing.

For example, I have my car object., that has two properties, Window, and Door., each one, Its an Object property.

Dim WCar = new Car with {.Door = new Door with {.Color = black}}

new Mgbox(WCar.Door.ToString & _
      WCar.Window.ToString) -> This may throw a null pointer exception.

(I do not own the class of the entity itself, and either know if this is safely coded in the constructor of the entity)

LarsTech
  • 77,282
  • 14
  • 135
  • 204

2 Answers2

2

You can use the null-conditional operator:

WCar.Window?.ToString()

If Window is Nothing this won't throw a NullReferenceException anymore, but ToString will return Nothing instead. If WCar could also be Nothing:

WCar?.Window?.ToString()
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
1

Maybe you can try to inherit the class and create your own setter and getter and validate if the property is null

polzka90
  • 125
  • 9