You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If a null-coalescing operator is used in a more complex statement, precedence should be declared to guarantee that the order of operation matches the intention.
Example
Consider this code example: the developer wants to add the nullable integers a and b together and store the outcome in c. Using null-coalescing operators, the developer intends to substitute a and b independently with 0.
int? a = 1;
int? b = 3;
var c = a ?? 0 + b ?? 0;
Developer's expectation: c = 1 + 3
Actual outcome: c = 1
Developer's intended order of execution:
var c = (a ?? 0) + (b ?? 0);
The actual order of execution of the calculation in the example is as follows:
var c = a ?? (0 + (b ?? 0));
If a has a value, a is returned instead of the intended outcome of a + b.
Conclusion
A rule reminding the developer to declare precedence when using null-coalescing operators would be a good addition, as it would help prevent unintended outcomes.
Up for discussion
This could be a new rule, but it's also loosely related to SA1407ArithmeticExpressionsMustDeclarePrecedence so it could be desirable to add the null-coalescing operator to SA1407 as another operator considered in this rule.
The text was updated successfully, but these errors were encountered:
If a null-coalescing operator is used in a more complex statement, precedence should be declared to guarantee that the order of operation matches the intention.
Example
Consider this code example: the developer wants to add the nullable integers
a
andb
together and store the outcome inc
. Using null-coalescing operators, the developer intends to substitutea
andb
independently with0
.Developer's expectation:
c = 1 + 3
Actual outcome:
c = 1
Developer's intended order of execution:
The actual order of execution of the calculation in the example is as follows:
If
a
has a value,a
is returned instead of the intended outcome ofa + b
.Conclusion
A rule reminding the developer to declare precedence when using null-coalescing operators would be a good addition, as it would help prevent unintended outcomes.
Up for discussion
This could be a new rule, but it's also loosely related to SA1407ArithmeticExpressionsMustDeclarePrecedence so it could be desirable to add the null-coalescing operator to SA1407 as another operator considered in this rule.
The text was updated successfully, but these errors were encountered: