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.

A bool? (nullable boolean) is the documented exception: bool? does not implicitly convert to bool, so if (flag) does not compile when flag is bool? — comparing with the literal is the required idiom, not a redundancy. This covers both a null-conditional access (items?.Any() == true, which lifts the result to bool?) and any operand already declared bool? — a nullable-bool field, property, parameter, local variable, or a generic call explicitly instantiated with bool? (e.g. Foo<bool?>(…​)).

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
return items?.Any() == true;      // OK — bool? lifted by ?.
return nullableFlag == true;      // OK — 'nullableFlag' declared 'bool?'

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.