Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do i need to put the null-coalescing operator in brackets?

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

like image 318
Tim Schmelter Avatar asked Jun 28 '13 15:06

Tim Schmelter


2 Answers

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.

like image 151
dlev Avatar answered Oct 03 '22 04:10

dlev


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.

like image 39
terrybozzio Avatar answered Oct 03 '22 04:10

terrybozzio