BRO1407: Conditional expressions should declare precedence¶
&&, || and ?? aren't mixed without parentheses, and neither are the and and or patterns.
Replaces StyleCop SA1408.
Example¶
Before¶
public class Access
{
public bool CanEdit(bool admin, bool owner, bool locked, int level) =>
admin || owner && !locked || level is > 5 and < 9 or 10;
}
After¶
public class Access
{
public bool CanEdit(bool admin, bool owner, bool locked, int level) =>
admin || (owner && !locked) || level is (> 5 and < 9) or 10;
}
Why¶
&& binds tighter than ||, and both bind tighter than ??, but readers often don't remember that, and a misread
condition is a bug.
How the fix works¶
The && (or and) operand of an || (or or) gets parentheses. So does an && or || operand of a ??:
// Before
var a = enabled ?? ready && open;
var b = enabled ?? ready || open;
var c = first && second ?? fallback;
// After
var a = enabled ?? (ready && open);
var b = enabled ?? (ready || open);
var c = (first && second) ?? fallback;
A chain of one operator (a ?? b ?? c) and a ?? next to other operators (count ?? a + b, enabled ?? a == b) 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; 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 &&, || and ??.
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity