This question already has an answer here:
- Deep Null checking, is there a better way? 17 answers
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.
f
method is definitely too messy. It makes the line of code shorter, but I'd say ternary is easier to understand. Thetc
method is pretty close, but throws an exception in the method which is a performance penalty (especially compared to a null check). So close, but not exactly what I'd hope for. – Syon Jul 26 '13 at 17:39