Given the following excerpt:
double value = 10;
string text = null;
double result = value - text?.Length ?? 0;
the result is 0 and I can't wrap my head around the actual operations taking place here.
I would have thought that result would be 10 instead given the precedence of the operators as I understand them:
- ?. is evaluated first
- The - operator should evaluate next since it has more priority than ??
- ?? should be evaluated last.
What is going on?
Don't be fooled by the new syntax, it's just a subtraction against null. Attempting to subtract null is short circuiting the subtraction statement, resulting in null itself. That is why it boils down to
?? 0
and you get 0 overall. The??
is allowing the short circuit. Without it you'd get an obvious compiler error.For example, lets remove the new syntax and write is as:
So the subtraction does take precedence but it's outcome is transformed (by the allowance a null short circuit) due to the introduction of the null coalescing operator.
Personally I feel the above should be a compiler error as well since it just has such an ambiguous feel to it. Visually it doesn't really make sense nor (at least in my opinion) would I approve of code written like this. Explicit parenthesis are a must.