Skip to content

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

Open
@b-jeltes-tjip

Description

@b-jeltes-tjip

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions