#213 – Final Operand When Using Null-Coalescing (??) Operator

You can use several ?? (null-coalescing) operators in a single expression.  For example:

    int result = i ?? j ?? k ?? 0;    // i, j and k are all of type int?

Notice that the final operand in the long expression is an integer constant.  If we tried to use an int? variable as the final operand, we’d get a compile-time error indicating that we can’t implicitly convert the int? to an int.  (Because the int? variable might be null, which can’t be assigned to an int).

    int result = i ?? j ?? k;    // Compile-time error

Whenever you use this form of an expression with the ?? operator, assigning a value to a non-nullable type, the type of the 2nd operand must match the type of the variable being assigned to.  (Or be implicitly converted to the target type).

Advertisements