Math.Abs. An absolute value is not negative. It is the same as the original value but with no negative sign. With absolute values, we can avoid accessing negative indexes in arrays.
Method info. The Math.Abs method in .NET provides a tested absolute value function. It deals with certain edge cases (like already-positive numbers).
Required input, output. Consider the values -1000 and 20. When we convert them into their absolute values, we get 1000 and 20—the minus sign is eliminated.
-1000
Abs() 1000
20
Abs() 20
Example. It is usually trivial to convert variables to positive values from negative values. The Math.Abs method provides some error-checking that may be useful.
Tip The C# compiler does overload resolution based on the parameter type. It infers the appropriate method to use.
Internals. Math.Abs() on value types (int, short, long) will use a conditional check that tests if the number if already positive. If the number is positive, it is returned unchanged.
Detail An overflow condition is checked and the unary negation operator is applied, which results in a positive number.
Tip If the overflow condition is not useful, you can enhance performance by checking for positive numbers yourself.
Notes, other types. For number types such as decimal, double and float, other implementations are called. Math.Abs is a wrapper method in these cases.
Tip For double and float, it is important to use Math.Abs instead of checking for positive yourself.
Discussion. From the hardware perspective, it is easier to flip the sign bit on a signed integer type. You can apply the unary minus (negation) operator.
Tip You can take the absolute value of a number that is always negative by simply using the unary negation operator.
Summary. We tested Math.Abs, an absolute value function. This method accepts decimal, double, Int16, Int32, Int64 and float types (and all keywords that are aliased to those).
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 11, 2023 (edit).