Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-coalescing operator

I have the following code:

decimal? a = 2m;
decimal? b = 2m;
decimal c = a ?? 1m * b ?? 1m;

Since both a and b have been filled in, I'm expecting c to give me the result of 4.

However, the result I get is 2, in which case b is taken as 1 instead of 2.

Does anyone know what is the reason behind this behaviour?

like image 754
matt Avatar asked Dec 15 '22 19:12

matt


2 Answers

group the value condition if you want to get the value of 4

decimal c = (a ?? 1m) * (b ?? 1m);

your current syntax is evaluated as

decimal c = a ?? (1m * b ?? 1m);

and the reason why you get the value of 2 (as for a)

like image 128
John Woo Avatar answered Jan 03 '23 21:01

John Woo


The expression works as:

decimal c = a ?? (1m * b) ?? 1m;

As a has a value, you get that.

like image 25
Guffa Avatar answered Jan 03 '23 22:01

Guffa