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?
Is there any easier way of formulating this expression?
With C# 6, you can use the null-conditional operator ?
.
This is your original code packed into a method and assuming Sniff()
always returns true
:
public bool PerformNullCheckVersion1(Person person)
{
if (person != null)
if (person.Head != null)
if (person.Head.Nose != null)
return person.Head.Nose.Sniff();
return false;
}
This is your code rewritten with the C# 6 null-conditional operator:
public bool PerformNullCheckVersion2(Person person)
{
return person?.Head?.Nose?.Sniff() ?? false;
}
The ??
is the null-coalescing operator and is not related to your question.
For the full example, see: https://github.com/lernkurve/Stackoverflow-question-3701563