Skip to content

New rule proposal: Do not use nullable variables in arithmetic #3891

Open
@b-jeltes-tjip

Description

@b-jeltes-tjip

Nullable values in arithmetic result in a null value when any of the variables are null. A developer might expect a null int? to be considered as 0.

Example

Consider this code example, where the developer adds nullable integers a and b together, and store it in c. The developer expects a null value to be considered as "0".

Non-compliant code

int? a = null;
int? b = 3;

var c = a + b;

Developer's expectation: c == 3
Actual outcome: c == null

Compliant code

Compliant code would substitute the value within the arithmetic operation:

var c = (a ?? 0) + (b ?? 0);

Or use non-nullable variables like this:

int aSubstituted = a ?? 0;
int bSubstituted = b ?? 0;

var c = aSubstituted + bSubstituted;

Conclusion

The developer should be reminded to not use nullable variables in arithmetic, or to provide a non-null value as a substitute to prevent unexpected outcomes.

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