Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid multiple if null checks [duplicate]

Tags:

c#

null

Possible Duplicates:
Deep Null checking, is there a better way?
C# elegant way to check if a property's property is null

i have to do a lookup in a deep object model like this:

  p.OrganisationalUnit.Parent.Head.CurrentAllocation.Person;

is there anyway to evalute this and return null if any of the chain is null (organizationalunit, parent, head, etc), without having to do a

if (p.org == null && p.org.Parent == null && p.org.Parent.Head . . .     
like image 348
leora Avatar asked Oct 09 '10 18:10

leora


People also ask

How to avoid null checks?

One way of avoiding returning null is using the Null Object pattern. Basically you return a special case object that implements the expected interface. Instead of returning null you can implement some kind of default behavior for the object. Returning a null object can be considered as returning a neutral value.

Are null checks bad?

But also the code in the function we are calling should never return null. Null checks are bad but returning null is also equally bad. There are many things the called function could do to avoid returning null.


2 Answers

You are looking for the null-safe dereference operator ?. (also known as safe navigation) that some languages (e.g. Groovy) have, but unfortunately C# does not have this operator.

Hopefully it will be implemented one day....

See also this post by Eric Lippert. The syntax he proposes there is .?.

like image 151
Mark Byers Avatar answered Oct 01 '22 19:10

Mark Byers


Have you heard of the Law of Demeter?

Chaining such long sequences of calls is not a good idea. It creates awful dependencies between classes that you don't need.

In your example, the class containing p becomes dependent of five other classes. I suggest you simplify your code and make each class check for nulls at a single level, in their own context of knowledge.

like image 20
CesarGon Avatar answered Oct 01 '22 19:10

CesarGon