Do not use the conditional operator (?:) where either the second or third
operand is a bool literal (true or false), resulting in bool values.
Warning
There are some stinky boolean expressions with a conditional operator that can
be replaced with the && (conditional logical AND) or || (conditional logical
OR) operator, as follows:
(b1 ? b2 : false)
(b1 ? true : b2)where the type of b1 and b2 is bool. It is possible to replace the former
conditional expression with b1 && b2, the latter with b1 || b2.
Conditional expressions where the second or third operand is a throw expression are not covered, as follows:
(b ? true : throw new Exception(…))The diagnostics IDE0057 providing Simplify conditional expressions refactoring, which is available with Visual Studio 2019 version 16.6 preview 2, includes the same feature as this analyzer.
The code fix provides an option replacing the conditional operator with the &&
or || operator. However, if the diagnostics IDE0057 provides an option
"Simplify conditional expression" with Visual Studio, you should use it.
_ = (b1 ? b2 : false);
_ = (b1 ? false : b2);
_ = (b1 ? true : b2);
_ = (b1 ? b2 : true);_ = ((b1) && (b2));
_ = (!(b1) && (b2));
_ = ((b1) || (b2));
_ = (!(b1) || (b2));