-1

Suppose I have a fairly deep class, and I need to get some field embedded deep within

int? result = this.child.button.data;
return result;

And at any point, it could be pointing to a null, in which case I want to return null as well. A common approach would be

if (this.child != null && this.child.button!= null) {
  return this.child.button.data;
} else {
  return null;
}

But if the field is REALLY deep nested, then the only solution I can think of is this:

int? result = null;
try {
  result = this.child.button.handler.controller.renderer.data;
} catch (NullReferenceException ex) {
  // Do nothing here
}

Is this the correct approach, or is there a better solution?

Yifei Xu
  • 777
  • 1
  • 6
  • 14
  • No, just use the null-conditional operator, like `this?.child?.button.handler.controller?.renderer?.data`. It will be checked for nulls wherever the ? is, and if any part of the expression leads to null, so will be the result – Icepickle May 29 '19 at 21:50

1 Answers1

1

you may check the null conditional operator in C# - ?. Like:

result = this?.child?.button?.handler?.controller?.renderer?.data;
Vishnu
  • 897
  • 6
  • 13