Wednesday, May 19, 2010

Call chain that could be null at any step. Enter IfNotNull or Maybe.

It could be called IfNotNull or Maybe, currently i'm going with Maybe.

Project available at

So we've all had to write code like

if(one==null) return null;
if(one.two==null) return null;
if(one.two.three==null) return null;
return one.two.three.four;

Now there's code to do it all in one fell swoop.

return one.Maybe(o=>o.two.three.four);

It also handles primitives not just classes:

return one.MaybeNullable(o=>o.two.three, t=>t.four);


Inspired by:


Some reading on the subject:

Note to self: Answer this once posted: