Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resharper pattern to detect arithmetic with nullable types

Tags:

c#

resharper

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.

like image 436
cbp Avatar asked Jul 23 '12 06:07

cbp


1 Answers

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.

like image 70
cbp Avatar answered Nov 16 '22 10:11

cbp