Barış Kısır

Senior Software Developer

Navigation
 » Home
 » RSS

Null Conditional Operator in Object Hierarchy

24 Aug 2017 » csharp

We have an object hierarchy at below.

class Employee
{
    public string Name { get; set; }
    public Address Address { get; set; }
}
class Address
{
    public string City { get; set; }
    public string State { get; set; }
}

In this case, I want to get employee’s state.

Before C# 6, I need to put some null controls like this.

string employeeState;

if (employee != null && employee.Address != null && employee.Address.State != null)
{
    employeeState = employee.Address.State;
}

With C# 6, we can make like this even though employee or employee.Address is null. If one of them is null, result will be null as well.

string employeeState = employee?.Address?.State;