C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: The C# compiler does overload resolution based on the parameter type. It infers the appropriate method to use.
OverloadCast: You could cast the variables before passing them as parameters to force the compiler to use a different overload.
Numeric CastsCast, IntNext: This example shows the absolute value of a negative integer, a positive integer, a negative double and a positive double.
Int, uintDoubleOutput: The example program prints 8 numbers. It prints the numbers, and their absolute values.
ConsoleC# program that computes absolute values
using System;
class Program
{
static void Main()
{
//
// Compute two absolute values.
//
int value1 = -1000;
int value2 = 20;
int abs1 = Math.Abs(value1);
int abs2 = Math.Abs(value2);
//
// Write integral results.
//
Console.WriteLine(value1);
Console.WriteLine(abs1);
Console.WriteLine(value2);
Console.WriteLine(abs2);
//
// Compute two double absolute values.
//
double value3 = -100.123;
double value4 = 20.20;
double abs3 = Math.Abs(value3);
double abs4 = Math.Abs(value4);
//
// Write double results.
//
Console.WriteLine(value3);
Console.WriteLine(abs3);
Console.WriteLine(value4);
Console.WriteLine(abs4);
}
}
Output
-1000
1000 (Absolute value)
20
20 (Absolute value)
-100.123
100.123 (Absolute value)
20.2
20.2 (Absolute value)
Tip: The external method invoked is likely much faster and simpler. This is often the case in the .NET Framework.
Tip: You can take the absolute value of a number that is always negative by simply using the unary negation operator.