Code inspection: Math.Abs() argument is always non-negative
This inspection reports usages of Math.Abs()
that are likely to be redundant because they have non-negative arguments.
The purpose of Math.Abs()
is to convert a potentially negative number to its non-negative equivalent. So if the argument is known to be non-negative, you can safely replace the Math.Abs()
call with the value of the argument.
To determine that the value of a variable or parameter is always non-negative, ReSharper relies on the integer arithmetic analysis, which is enabled by default.
In the example below, all three usages of Math.Abs()
will be reported because:
p1
is marked with the[NonNegativeValue]
attribute from JetBrains.Annotations that adds the corresponding contract,p2
is of the typeuint
, which can only contain non-negative values,p3
is non-negative, because it was explicitly checked in the source code.