In earlier versions of the C# language, you always had to write the explicit if condition NULL checks before using an object or its property, as shown below.
private void GetMiddleName(Employee employee)
{
string employeeMiddleName = "N/A";
if (employee != null && employee.EmployeeProfile
!= null)
employeeMiddleName =
employee.EmployeeProfile.MiddleName;
}
The same can be converted into a one-liner by using the Conditional Access Operator in C# 6.
private void GetMiddleName(Employee employee)
{
string employeeMiddleName =
employee?.EmployeeProfile?.MiddleName ?? "N/A";
}
Notice the default value provided on the same line of code.