-
Notifications
You must be signed in to change notification settings - Fork 23
SA1407
TypeName |
ArithmeticExpressionsMustDeclarePrecedence |
CheckId |
SA1407 |
Category |
Maintainability Rules |
A C# statement contains a complex arithmetic expression which omits parenthesis around operators.
C# maintains a hierarchy of precedence for arithmetic operators. It is possible in C# to string multiple arithmetic 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:
int x = 5 + y * b / 6 % z - 2;
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. The example below shows multiple arithmetic operations surrounded by parenthesis:
int x = 5 + (y * ((b / 6) % z)) - 2;
Inserting parenthesis makes the code more obvious and easy to understand, and removes the need for the reader to make assumptions about the code.
To fix a violation of this rule, insert parenthesis within the arithmetic expression to declare the precedence of the operations.
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1407:ArithmeticExpressionsMustDeclarePrecedence", Justification = "Reviewed.")]
- - SA0102 - Clean Install
- - Download
- - Documentation Rules - Layout Rules - Maintainability Rules - Naming Rules - Ordering Rules - Readability Rules - Spacing Rules - Suppressions
- - Adding a custom StyleCop settings page - Adding custom rule settings - Authoring a custom styleCop rule - Authoring rules metadata - Custom CSharp Language Service - Custom MSBuild Integration - Hosting StyleCop in a Custom Environment - Installing a Custom Rule - Integrating StyleCop Into Build Environments - Integrating StyleCop into MSBuild - Writing Custom Rules for StyleCop