No Nonexistent Operator
ID |
csharp.no_nonexistent_operator |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
CSharp |
Tags |
code_smell, suspicious-assignment, suspicious-operator |
Description
Reports an assignment written as target =- num, target =+ num or target =! flag, where the
= is glued to the unary operator that follows and the operand is set off by a space. C# has no
=-, =+ or =! operator, so the layout claims something the code does not do.
Rationale
The compiler reads target =- num as "assign the negation of num to target`". A reader
scanning the line sees the two glued characters as a single token and reads "subtract `num from
target`" — the compound assignment `-=. Both readings are plausible, only one is what runs, and
nothing in the build flags the difference. target =! flag is the same trap against !=:
it overwrites target where a comparison was intended, and the result still type-checks whenever
target is a bool.
This is a spacing defect rather than a structural one, so the rule uses token positions. The
unary operator must begin exactly where the = ends, on the same line, and whitespace must
separate it from its operand. Correctly spaced code (target = -num) and unambiguous tight code
(target =-num) are both accepted.
public class Counter
{
private int total;
private bool active;
public void Apply(int step, bool flag)
{
total =- step; // FLAW — assigns -step; reads as total -= step
total =+ step; // FLAW — assigns +step; reads as total += step
active =! flag; // FLAW — assigns !flag; reads as active != flag
total -= step; // OK — real compound assignment
total = -step; // OK — spacing matches the meaning
total =-step; // OK — nothing to misread
}
}
Remediation
Decide which of the two readings was meant. If the intent was to accumulate, use the compound
assignment (total -= step). If the intent really was to assign a signed or inverted value, put a
space after the = so the layout matches (total = -step). For the =! form, check whether a
comparison (!=) was intended before changing anything.