[C#] New rule proposal: Do not use nullable variables in arithmetic

Nullable values in arithmetic result in a null value when any of the variables are null.

Example

Consider this code example, where the developer adds nullable integers a and b together, and store it in c. In this example, 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.

Hi,

Welcome to the community!

I know it’s obvious to you, but it’s not obvious to me: what language is this? :sweat_smile:

 
Thx,
Ann

Hi there! Thanks for the warm welcome.
This is about C#. I thought I added it as a tag, but it wasn’t there, so thanks for pointing it out!

I’ve added the csharp tag and added it to the title for additional clarity as well.

Hi,

In fact, you put it there initially, but some automation we’re testing (and have now turned off :sweat_smile:) wiped it out. Sorry about that.

And I’ve flagged this for the language experts.

 
Ann

It seems like a language feature is used here in a straightforward way, which I would say is permitted.

By the way, SQL null behaves the same way in arithmetic. The idea is that null means “unknown”.

Hi there, @bje

I realize I forgot to thanks you for the suggestion!
We recorded it into our list of potential rules to be added to the csharp language.

Denis

For those who already want a rule that does excactly this:

QW0017: Apply arithmetic operations on non-nullables only

And the NuGet package: NuGet Gallery | Qowaiv.Analyzers.CSharp 2.0.4