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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With