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: Do not use nullable variables in arithmetic #3891

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

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

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

Comments

@b-jeltes-tjip
Copy link

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.

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