?[]
Section 13.9 introduced nullable types and C# 6’s null-conditional operator (?.
), which checks whether a reference is null
before using it to call a method or access a property. C# 6 provides another null-conditional operator, ?[]
, for arrays and for collections that support the []
indexing operator.
Assume that a class Employee
has a decimal Salary
property and that an app defines a List<Employee>
named employees
. The statement
decimal? salary = employees?[0]?.Salary;
uses both null-conditional operators and executes as follows:
First the ?[]
operator determines whether employees
is null
. If so, the expression employees?[0]?.Salary
short circuits—that is, it terminates immediately—and the expression evaluates to null
. In the preceding statement, this is assigned to the nullable decimal
variable salary
. If employees
is not null
, employees?[0]
accesses the element at position 0
of the List<Employee>
.
Element 0
could be null
or a reference to an Employee
object, so we use the ?.
operator to check whether employees?
[0
] is null
. If so, once again the entire expression evaluates to null
, which is assigned to the nullable decimal
variable salary
; otherwise, the property Salary
’s value is assigned to salary
.
Note in the preceding statement that salary
must be declared as a nullable type, because the expression employees?
[0
]?.Salary can return null
or a decimal
value.