Can someone explain the precedence rules using the C# 6.0 ?. operator with ?? and arithmetic ops?

262 Views Asked by At

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:

  1. ?. is evaluated first
  2. The - operator should evaluate next since it has more priority than ??
  3. ?? should be evaluated last.

What is going on?

2

There are 2 best solutions below

1
On BEST ANSWER

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:

Console.WriteLine(10 - null ?? 0);
// Prints 0

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.

0
On
double result = value - text?.Length ?? 0;

this can be disglossed as:

result = (value -  text)==null ? 0
(10 -  null)==null ? 0 
null == null ? 0 

which is 0