How to detect nulls in a nested object hierarchy

I’ve been trying to find a ‘nice’ solution to a problem I’ve encountered in the past. I’ve tried searching for it but I’m not sure I know the right words to explain what I want to do.

 The problem is: when you have an object of interest that is nested at a deep level within other objects how do you check for null values? For example if you have:

ObjectA.ObjectB.ObjectC.ObjectD.Name

And you want to get the value of Name, how do you get at it? Specifically how do you handle any of Objects A,B,C or D being null?

Option 1 – try…catch:

I think this might be the ‘right’ way, but it doesn’t feel quite right, I don’t like using try…catch for ‘expected’ cases:

string Name=null;
try{
	Name=ObjectA.ObjectB.ObjectC.ObjectD.Name;
}catch(NullReferenceException ex){
	//do something

}

Option 2 – check for each null:

string Name=null;

if(ObjectA==null){
//case1;
}else if(ObjectB==null){
//case2;
}else if(ObjectC==null){
//case3;
}else if(ObjectD==null){
//case4;
}else{
Name=ObjectA.ObjectB.ObjectC.ObjectD.Name;
}

This option feels horrible in many ways, and what happens if there is a depth of 20 objects?

Option 3 – something else

It really feels like there should be something else to do this, but I just can’t seem to find it. Any suggestions?

1 comment so far

  1. Vincent Hendriks on

    What about just doing this:

    if (ObjectA != null && ObjectA.OBjectB != null && ObjectA.ObjectB.ObjectC != null && ObjectA.ObjectB.ObjectC.ObjectD != null)
    {
    Name = ObjectA.ObjectB.ObjectC.ObjectD.Name;
    }

    ?

    I agree with you that Option 1 is not a real option. Option 2 is a bit like what i just said, but a bit more verbose. I usually use this way anyhow. A depth of 20 classes sounds a bit funny tbh, never ever reached that depth. I think that if you actually do reach it, you’re probably doing something else wrong hehe :D

    I think you can never get this “perfect” but i guess there ain’t that many other options. Well, besides using reflection types of doing it or auto-generated code ;)

    Best Regards,
    Vincent


Leave a reply