Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null checks in nested objects [duplicate]

Tags:

c#

null

I have several plain old C# objects that are returned by an API, and have several layers of POCOs nested within them. I need to access fields contained deep within these structures, but because the API leaves these nested objects as null when data is missing, I find myself having to do lots of null checks just to get at the field I really want.

if(obj != null && obj.Inner != null && obj.Inner.Innerer != null) { ... }

The shortest form I've come up with is using the ternary operator.

obj != null && obj.Inner != null && obj.Inner.Innerer != null ? obj.Inner.Innerer.Field : null;

Does C# have any way to do this without having to write out all those comparisons? I'd really like something short and simple like:

obj.Inner.Innerer.Field ?? null;

But that only checks Field for null.

like image 972
Syon Avatar asked Jul 26 '13 17:07

Syon


People also ask

How do I avoid multiple nulls in Java 8?

We can get rid of all those null checks by utilizing the Java 8 Optional type. The method map accepts a lambda expression of type Function and automatically wraps each function result into an Optional . That enables us to pipe multiple map operations in a row.

Is Java null safe?

The reason is that Java does not support null safety, and non-nullable types do not exist. In other terms, any variable is always a nullable reference and there is no way to avoid null values except with custom logic. Thus, any reference in Java may be null by default.

How can you tell if an object is nested?

To check if an object has a nested property, use the optional chaining operator - ?. . The ?. operator allows you to read the value of a nested property without throwing an error if the property does not exist on the object, e.g. obj?. a?.


1 Answers

Please have a look at this very clever and elegant solution:

http://www.codeproject.com/Articles/109026/Chained-null-checks-and-the-Maybe-monad

like image 55
RX_DID_RX Avatar answered Oct 30 '22 19:10

RX_DID_RX