In C#, is there a clean way of checking for multiple levels of null references

Andrew Ducker picture Andrew Ducker · Sep 13, 2010 · Viewed 7.9k times · Source

For example, if I want to call the following: person.Head.Nose.Sniff() then, if I want to be safe, I have to do the following:

if(person != null)
    if(person.Head != null)
        if(person.Head.Nose != null)
            person.Head.Nose.Sniff();

Is there any easier way of formulating this expression?

Answer

João Angelo picture João Angelo · Sep 13, 2010

First you can take advantage of short-circuiting in the boolean logic operators and do something like:

if (person != null && person.Head != null && person.Head.Nose != null)
{
    person.Head.Nose.Sniff();
}

Also note that what you are doing goes against a design guideline for developing software that is known as Law of Demeter.