Zero checks in nested objects

I have some simple old C # objects that are returned by the API, and have several layers of POCOs nested within them. I need to access the fields contained within these structures, but since the API leaves these nested objects empty when data is missing, I have to do a lot of null checks just to get into the field that I really want.

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

The shortest form I came up with is using a 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 writing all these comparisons? I would really like something short and simple:

 obj.Inner.Innerer.Field ?? null; 

But this only checks the field for null.

+7
null c #
source share
2 answers

Please take a look at this very smart and elegant solution:

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

+1
source share

This is not beautiful, but you could write access functions in your code that encapsulated null checks, so you only need to do this in one place. For example.

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

So you can call it this way: if (myObject.GetInnerer() != null)... You would need to create a number of these functions, but at least it would move the "goreyness" of the zero check to one place.

0
source share

All Articles