BRO1103: Constants should be on the right-hand side of comparisons¶
0 == count should be written as count == 0. Replaces StyleCop SA1131.
Example¶
Before¶
public class Stock
{
public bool IsEmpty(int count) => 0 == count;
public bool IsLow(int count) => 10 > count;
}
After¶
public class Stock
{
public bool IsEmpty(int count) => count == 0;
public bool IsLow(int count) => count < 10;
}
Why¶
count == 0 reads the way you'd say it: "count is zero". The "constant first" style (0 == count) guarded against
typing = for == in C, but in C# that mistake doesn't compile for most types anyway.
What is reported¶
Comparisons (==, !=, <, >, <=, >=) with a constant on the left and a non-constant on the right. Like
StyleCop, "constant" means literals, null, default, const fields, enum members, nameof(...), constant
expressions such as 1 + 1, and static readonly fields such as string.Empty.
How the fix works¶
The fix swaps the operands and flips relational operators (10 > count becomes count < 10). Line breaks and
comments stay where they are. 1 == 2 == b becomes b == (1 == 2), keeping its meaning. Nested comparisons are
fixed in one pass.
Not reported¶
- Comparisons that use a type's own operator, such as
null == moneywhereMoneydefines==. A hand-written operator isn't guaranteed to give the same result with its operands reversed, and reversing them can even pick a different overload. Operators from the .NET core library (string,decimal,DateTime,Guid, ...) are symmetric, soGuid.Empty == idis still reported. - Comparisons with a constant on both sides (
1 == 2), like StyleCop.
Compared with StyleCop¶
StyleCop also swaps comparisons that use a type's own operator.