5

I have recently noticed a curiosity (at least for me). I thought that the null-coalescing operator would take the precedence over any mathematical operation but obviously i was wrong. I thought following two variables would have the same value at the end:

double? previousValue = null;
double? v1 = 1 + previousValue ?? 0;
double? v2 = 1 + (previousValue ?? 0);

But v2.Value is (the desired) 1 whereas v1.Value is still 0. Why?

Demo

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • might help: http://en.csharp-online.net/ECMA-334%3a_14.2.1_Operator_precedence_and_associativity also http://stackoverflow.com/questions/511093/what-is-the-operator-precedence-of-c-sharp-null-coalescing-operator – Ric Jun 28 '13 at 15:33

2 Answers2

8

v1 is 0 for the exact reason you mentioned: the null-coalescing operator actually has relatively low precedence. This table shows exactly how low.

So for the first expression, 1 + null is evaluated first, and it evaluates to a null int?, which then coalesces to 0.

dlev
  • 48,024
  • 5
  • 125
  • 132
1

v2 is saying,1 plus (if previousValue == null add to 1 the value 0,which gives 1.The v1 is saying 1 plus null is null so lets give back the 0.

terrybozzio
  • 4,424
  • 1
  • 19
  • 25