Deep Null checking, is there a better way?

Posted by Mattias Konradsson on Stack Overflow See other posts from Stack Overflow or by Mattias Konradsson
Published on 2010-01-17T10:17:39Z Indexed on 2010/03/13 20:25 UTC
Read the original article Hit count: 291

Filed under:
|

We've all been there, we have some deep property like cake.frosting.berries.loader that we need to check if it's null so there's no exception. The way to do is is to use a short-circuiting if statement

if (cake != null && cake.frosting != null && cake.frosting.berries != null) ...

This strikes me however as not very elegant, there should perhaps be an easier way to check the entire chain and see if it comes up against a null variable/property.

So is it possible using some extension method or would it be a language feature, or is it just a bad idea?

© Stack Overflow or respective owner

Related posts about c#

Related posts about null