Why is this an issue?
When using the postfix
increment operator, it is important to know that the result of the expression x++ is the value before the operation
x.
This means that in some cases, the result might not be what you expect:
- When assigning
x++tox, it’s the same as assigningxto itself, since the value is assigned before the increment takes place - When returning
x++, the returning value isx, notx+1
The same applies to the postfix and prefix decrement operators.
How to fix it
To solve the issue in assignments, eliminate the assignment, since x\++ mutates x anyways.
To solve the issue in return statements, consider using the prefix
increment operator, since it works in reverse: the result of the expression ++x is the value after the operation,
which is x+1, as one might expect.
The same applies to the postfix and prefix decrement operators.
Code examples
Noncompliant code example
int PickNumber()
{
int i = 0;
int j = 0;
i = i++; // Noncompliant: i is still 0
return j--; // Noncompliant: returns 0
}
Compliant solution
int PickNumber()
{
int i = 0;
int j = 0;
i++; // Compliant: i is incremented to 1
return --j; // Compliant: returns -1
}
Resources
Documentation
- Microsoft Learn - Arithmetic operators (C# reference)