Skip to content

BRO1406: Arithmetic expressions should declare precedence

An operation inside an arithmetic 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.

How the fix works

The operand gets parentheses. The families are + -, * / and << >>; % is a family of its own, so a * b % c becomes (a * b) % c. Operations of the same family (a + b - c) are left alone. Nested operands get all their parentheses in one pass.

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.
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity

Compared with StyleCop

Same positions and output.