TypeName | ConditionalExpressionsMustDeclarePrecedence |
CheckId | SA1408 |
Category | Maintainability Rules |
Cause
A C# statement contains a complex conditional expression which omits parenthesis around operators.
Rule Description
C# maintains a hierarchy of precedence for conditional operators. It is possible in C# to string multiple conditional operations together in one statement without wrapping any of the operations in parenthesis, in which case the compiler will automatically set the order and precedence of the operations based on these pre-established rules. For example:
if (x || y && z && a || b)
{
}
Although this code is legal, it is not highly readable or maintainable. In order to achieve full understanding of this code, the developer must know and understand the basic operator precedence rules in C#.
This rule is intended to increase the readability and maintainability of this type of code, and to reduce the risk of introducing bugs later, by forcing the developer to insert parenthesis to explicitly declare the operator precedence. For example, a developer could write this code as:
if ((x || y) && z && (a || b))
{
}
or
if (x || (y && z && a) || b)
{
}
Inserting parenthesis makes the code more obvious and easy to understand, and removes the need for the reader to make assumptions about the code.
How to Fix Violations
Insert parenthesis within the conditional expression to declare the precedence of the operations.