Assignment In Conditional
ID |
csharp.assignment_in_conditional |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
CSharp |
Tags |
reliability, suspicious-comparison |
Description
Reports a simple assignment (x = expr) appearing in the condition expression of an
if, while, do … while, or for statement. A simple assignment in a boolean
context is almost always a typo for ==. In C# the typo only compiles when the assigned
value is itself bool, which makes the mistake easy to overlook in code review.
Rationale
if (x = something) evaluates something and assigns it to x, then uses the assigned
value as the condition. The intended code is almost always if (x == something). The
rule excludes compound assignments (+=, -=, ??=, …) because they occasionally
appear legitimately inside loop headers.
if (ok = TryParse(s)) // FLAW — simple assignment in condition
{
Use(s);
}
while (running = Poll()) // FLAW — assignment, not comparison
{
Step();
}
if (ok == TryParse(s)) // OK — proper comparison
{
Use(s);
}
Remediation
If a comparison was meant, change = to ==. If the assignment was intentional, lift it
out of the condition into a preceding statement, or wrap it in extra parentheses to make
the intent obvious.