You can fix NullReferenceExceptionNullReferenceException in a clean way using Null-conditional Operators in C# 6 and write less code to handle null checks.
It's used to test for null before performing a member access (?.) or index (?[) operation.
Example
var name = p?.Spouse?.FirstName;
It is equivalent to:
if (p != null)
{
if (p.Spouse != null)
{
name = p.Spouse.FirstName;
}
}
The result is that the name will be null when p is null or when p.Spousep.Spouse is null.
Otherwise, the variable name will be assigned the value of the p.Spouse.FirstNamep.Spouse.FirstName.
For more details: Null-conditional Operators