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
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.
The text was updated successfully, but these errors were encountered:
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
andb
together, and store it inc
. The developer expects a null value to be considered as "0".Non-compliant code
Developer's expectation:
c == 3
Actual outcome:
c == null
Compliant code
Compliant code would substitute the value within the arithmetic operation:
Or use non-nullable variables like this:
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.
The text was updated successfully, but these errors were encountered: