BRO1406: Arithmetic expressions should declare precedence¶
An operation inside an arithmetic, shift or bitwise operation of another kind is in parentheses. Replaces StyleCop SA1407.
Example¶
Before¶
public class Prices
{
public int Total(int price, int count, int fee, int mask) =>
price * count + fee >> mask % 4;
}
After¶
public class Prices
{
public int Total(int price, int count, int fee, int mask) =>
((price * count) + fee) >> (mask % 4);
}
Why¶
Precedence between +, *, %, <<, & and | is easy to get wrong when reading; parentheses say what the code
does. flags & mask == 0 compares first: flags & (mask == 0) shows it.
How the fix works¶
The operand gets parentheses. The families are + -, * / and << >> >>>; %, &, | and ^ are each a family
of their own, so a * b % c becomes (a * b) % c and a & b | c becomes (a & b) | c. Operations of the same
family (a + b - c, a | b | c) are left alone. Nested operands get all their parentheses in one pass.
Under &, | and ^ a comparison (==, <, is, as) is an operation of another kind too:
// Before
var merged = a & b | c;
var mixed = a ^ b + c;
var shifted = a + b >>> c;
var both = a == b & c == d;
var text = ready & value is string;
// After
var merged = (a & b) | c;
var mixed = a ^ (b + c);
var shifted = (a + b) >>> c;
var both = (a == b) & (c == d);
var text = ready & (value is string);
An operation under &&, ||, ??, a comparison or the conditional operator is left alone (a + b == c,
f || a & b); BRO1407 has &&, || and ??.
This rule replaces the SDK's IDE0048, whose fix writes merge conflict markers in multi-targeted projects under
dotnet format (reported upstream as dotnet/roslyn#86000) and needed a second run (see decisions).
Configuration¶
[*.cs]
# The SDK's setting: always_for_clarity (or not set) keeps this rule; never_if_unnecessary turns it off.
# It covers the arithmetic, shift and bitwise operators.
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity