Can anyone think of good Resharper pattern that will detect the following bug:
decimal? x = null;
decimal? y = 6M;
var total = x + y;
Console.WriteLine(total); // Result is null
I've tried creating a pattern but I can't work out how to quickly handle all types of arithmetic (e.g. +, -, * etc), and any nullable type (e.g. Nullable<int>, Nullable<decimal>, Nullable<double> etc
). Also I can't handle commutativity (e.g. it should detect x + y as well as y + x).
Note that I don't necessarily need to detect whether or not x is actually null: just whether or not it is a nullable type. I want to force developers to write: x.Value + y.Value.
This is not a full answer, but this is the best I've come up with so far.
The pattern is:
$obj$ + $nullableObj$
obj is an "expression of type System.Object or one of its derived types nullableObj is an "expression of type System.Nullable". (Note that you don't want nullableObj to include derived types).
This not a very good solution because the pattern doesn't handle commutativity, so you'll need to copy and paste it and reverse the expressions:
$nullableObj$ + $obj$
Also, this pattern only handles decimal, so you'll need to copy and paste it for each type that you interested in (yes, that's potentially a lot of patterns).
One piece of good news: The + symbol handles both addition and subtraction, so you don't need to worry about subtraction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With