ReSharper 2024.2 Help

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 type uint, which can only contain non-negative values,

  • p3 is non-negative, because it was explicitly checked in the source code.

public void Test([NonNegativeValue] int p1, uint p2, int p3) { Console.WriteLine("Abs 1:" + Math.Abs(p1)); Console.WriteLine("Abs 2:" + Math.Abs(p2)); if (p3 < 0) return; Console.WriteLine("Abs 1:" + Math.Abs(p3)); }
Last modified: 30 September 2024