A constant or literal value appears on the left side of a comparison operator instead of the right side; or is used to call the Equals method instead of being passed as its argument.
To increase readability, place constants on the right side of an operator, not the left; or pass the constant as argument to an Equals method call.
This makes the code look more intuitive and easier to understand.
The order of operands in comparisons affects how naturally the code reads. Placing variables on the left and constants on the right matches how comparisons are typically expressed in natural language and mathematics.
Following this convention provides several important benefits:
-
Improves Natural Reading Flow: The pattern
variable == constantreads like "is the variable equal to this value", which matches natural language. The reverse orderconstant == variablereads awkwardly and requires mental reversal to understand. -
Aligns with Mathematical Notation: In mathematics and everyday language, comparisons are typically written as "x equals 5" rather than "5 equals x". Following this convention makes code more intuitive for all developers.
-
Reduces Cognitive Load: When code follows expected patterns, developers can read it more quickly and with less mental effort. Consistent ordering reduces the need to consciously process the comparison direction.
-
Simplifies Code Reviews: Reviewers can scan through comparisons more efficiently when they follow a consistent pattern. Unexpected ordering can cause reviewers to pause and double-check the logic.
-
No Longer Needed for Safety: In older C-style languages, putting constants on the left prevented accidental assignment when
=was used instead of==. Modern C# compilers prevent this error, eliminating the original reason for constant-first comparisons. -
Maintains Consistency: Consistent ordering throughout the codebase makes the code more predictable and professional. Mixed styles create unnecessary variation that can distract from the actual logic.
To fix a violation of this rule, swap the operands of the comparison so that the variable appears on the left and the constant or literal appears on the right.
For example:
- change
5 == counttocount == 5, ornull == valuetovalue == null - change
42.Equals(count)tocount.Equals(42)
#pragma warning disable MiKo_3084
#pragma warning restore MiKo_3084