Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 319
Andrew Ducker Avatar asked Sep 13 '10 14:09

Andrew Ducker


People also ask

What is '~' in C language?

In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...

What does += mean in C?

+= Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A. -=


1 Answers

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.

like image 190
João Angelo Avatar answered Oct 06 '22 10:10

João Angelo