-
Notifications
You must be signed in to change notification settings - Fork 723
Description
Page URL
Page source
No response
Describe the problem
The guideline currently suggests using ?? <bool>
instead of == <bool>
or != <bool>
when dealing with a nullable Boolean. But the ??
operator often doesn't type promote in ways that you want, which is why the guideline also has a large exception that mostly cancels out the guidance.
Also, the examples all use ?.
, which makes it seem like the rule is advocating or at least has something to do with null-aware operators.
Really, the key point of the guideline is that equality operators are all very confusing when you have a Boolean literal on one side and a nullable Boolean expression on the other. If you see:
if (foo == true) { ... }
It appears to have nothing to do with null
and that the == true
is pointless and the code should instead be:
if (foo) { ... }
But that chances the behavior if foo
happens to be nullable. You could improve this code with:
if (foo ?? false) { ... }
Now the ??
operator makes it clear that something to do with null
is happening. But it's equally valid (and often better because of type promotion) to do:
if (foo != null && foo) { ... }
This guideline shouldn't be that ??
is good, it's more that == true
etc. are bad.
Expected fix
We should clearly target the guideline to the behavior we want to avoid. Something like: "DON'T use true
or false
in equality operators."
If the other operand isn't nullable, then it's always simpler to eliminate the equality operator and add !
if needed. If the other operand is nullable, you should use ??
or an explicit null check to make that clear.
Additional context
No response