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.
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.
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.
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?.
Please have a look at this very clever and elegant solution:
http://www.codeproject.com/Articles/109026/Chained-null-checks-and-the-Maybe-monad
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With