Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null coalescing operator, unpredictable behavior

Tags:

c#

dart

I feel confused about results of flow piece of code:

bool? _true = true;

bool? val1 = _true ?? true && false; //true
bool? val2 = (_true ?? true) && false; //false

I thought result should be the same, anyone can explain such as behavior? I noticed that it works identically at least in c# and dart so it means that should be good reason for that.

like image 431
Ilya Avatar asked Nov 28 '22 00:11

Ilya


2 Answers

This is because of operator precedence, the && operation is performed before ??. So your first line is equivalent to:

bool? val1 = _true ?? (true && false);
like image 105
DavidG Avatar answered Dec 05 '22 02:12

DavidG


The logical and operators (&&) have higher precedence than the null coalescing operator (??).

So

bool? val1 = _true ?? true && false; //true

is equal to _true ?? (true && false). Since _true is not null, the null coalescing operator returns this value (true).

In the second case

bool? val2 = (_true ?? true) && false; //false

the part in brackets is true again, but ANDed with false it results in false.

See C# operator precedence

like image 27
René Vogt Avatar answered Dec 05 '22 00:12

René Vogt