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?
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.