Search code examples
c#computer-science

Is "null-conditional operator" a misnomer?


It's my understanding that sub-expressions must always be evaluated before the parent expression.

(a + b) / (c + d)

In the above example, a + b and c + d are always evaluated before division. My understanding is that this is true even when a, b, c, and d are all nullable, and that this is the behavior of a true operator.

However, with the assumption that a is null and that these methods exist, if we write

(a?.Add(b))?.DivideBy(c?.Add(d))

none of the methods are executed, even when b, c, and d are not null.

Is it appropriate for ?. to be referred to as an operator, or is that a bastardization of the term?


Solution

  • According to the manual

    ?. and ?[] null-conditional Operators

    Tests the value of the left-hand operand for null before performing a member access (?.) or index (?[]) operation; returns null if the left-hand operand evaluates to null.

    (bold is mine). In your case

     (a?.Add(b))?.DivideBy(c?.Add(d))
    

    can be rewritten as

     a                        // a is null
       ?.Add(b)               // left is null? Yes; then propagate null - don't compute Add
       ?.DivideBy(c?.Add(d))  // left is null? Yes; then propagate null - don't exec DivideBy