Open
Description
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
Labels
No labels