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.
This is because of operator precedence, the && operation is performed before ??. So your first line is equivalent to:
bool? val1 = _true ?? (true && false);
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
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