Boolean Compare With Literal
ID |
csharp.boolean_compare_with_literal |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
CSharp |
Tags |
code-style, suspicious-comparison |
Description
Reports uses of == or != to compare a value against the boolean literals true or
false. Such comparisons are redundant: a boolean expression can be used directly or
negated.
Rationale
if (flag == true) is just a wordier if (flag), and if (flag == false) is if (!flag).
The extra comparison adds noise and is a frequent source of the classic typo where ==
is mistyped as = (an assignment) — a mistake the negation form cannot make. Using the
boolean directly is shorter, clearer and safer.
return flag == true; // FLAW — write: return flag;
return flag != false; // FLAW — write: return flag;
return true == flag; // FLAW — literal on the left
return flag; // OK — used directly
return x == y; // OK — not a boolean literal
Remediation
Use the boolean expression directly. Replace flag == true with flag, replace
flag == false or flag != true with !flag, and replace flag != false with flag.