Null-coalescing statement

I have the following code:

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

Since both a and b were filled, I expect c give me a result of 4 .

However, the result is 2 , and in this case b taken as 1 instead of 2 .

Does anyone know what is the reason for this behavior?

+4
source share
3 answers

The expression works like:

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

Since a matters, you get this.

+4
source

group value condition if you want to get value 4

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

your current syntax evaluates to

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

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

+5
source
 decimal c = a ?? 1m * b ?? 1m; 

Equality:

 if (a != null) c = a else ... 

In your case, a not null and has a value of 2 , so this is the result.

+3
source

Source: https://habr.com/ru/post/1436730/


All Articles