Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New rule proposal: Declare precedence when using null-coalescing operators #3890

Open
b-jeltes-tjip opened this issue Sep 17, 2024 · 0 comments

Comments

@b-jeltes-tjip
Copy link

b-jeltes-tjip commented Sep 17, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant