HomeSearch

C# Math.Max and Math.Min Examples

Use the Math.Max and Math.Min methods to get the higher or lower of 2 elements.
Math.Max, Min. Math.Max returns the larger value. It can improve code that calculates integer bounds. Min() does the same thing, but returns the lower value.
Often in algorithms we need to test if an integer is less than zero. We use Math.Max to test for these conditions with less code.Math
First example. We use the Math.Max method to check bounds. You can replace many if-statements with one line of code using Math.Max.If

And: We take the maximum of zero and the value. The result will never be less than zero.

GetLastIndex: This method internally uses the Math.Max function. It returns one index from the last index.

Return

Thus: If you pass in a number that is way too high, it won't cause an error in the calling code. It is safe and reliable.

C# program that uses Math using System; class Program { static int[] _array = new int[] { 1, 2, 5, 6, 7 }; static void Main() { // Get 1 place from end. int i = GetLastIndex(1); Console.WriteLine(i); // Get 3 places from end. i = GetLastIndex(3); Console.WriteLine(i); // Get 10 places from end. Will not throw exception. i = GetLastIndex(10); Console.WriteLine(i); } static int GetLastIndex(int length) { int start = _array.Length - length - 1; start = Math.Max(0, start); return _array[start]; } } Output 6 2 1
Example 2. You can rewrite if-statements to code that uses the Math class. It can make your code more maintainable. Testing bounds with if is bug-prone.

Important: Node how we have to remember the "less than" sign, in the first code, but the second program has fewer symbols.

So: The code that uses Math.Max may be easier to read, and may be less prone to typos.

C# program that uses if using System; class Program { static void Main() { // Constrain indexes with if-statement. int a = 4; if (a < 0) { Console.WriteLine(0); } else { Console.WriteLine(a); } } } C# program that uses Math.Max using System; class Program { static void Main() { // Constrain indexes with Math.Max. int a = 4; Console.WriteLine(Math.Max(0, a)); } }
Math.Min example. The Math.Min method returns the minimum of the 2 arguments you send to it. You need to send 2 numbers of the same type (int, uint, double or decimal).Int, uintDoubleDecimal

Casting: The C# language has complex rules for implicit casting, so this may occur when using Math.Min or similar Math methods.

Info: In both uses of Math.Min, the smaller of the two values (the identifiers value1, and value3) are returned.

Also: You cannot use null as a parameter or any reference type. The number zero can be used with Math.Min.

C# program that uses Math.Min using System; class Program { static void Main() { // // Use Math.Min on positive integers. // int value1 = 4; int value2 = 8; int minimum1 = Math.Min(value1, value2); Console.WriteLine(minimum1); // // Use Math.Min on negative and positive integers. // int value3 = -1000; int value4 = 100; int minimum2 = Math.Min(value3, value4); Console.WriteLine(minimum2); } } Output 4 -1000
Math.Min. Next we rewrite an if-condition expression to use the method Math.Min on integral types. This example caps values at a certain number using Math.Min.

Caution: Sometimes the Math.Max and Math.Min methods can be confused. Be careful to test after rewriting code to use them.

C# program that uses if using System; class Program { static void Main() { // Make sure it isn't > 10. int b = 15; if (b > 10) { b = 10; } Console.WriteLine(b); } } C# program that uses Math.Min using System; class Program { static void Main() { // Make sure it isn't > 10. int b = 15; Console.WriteLine(Math.Min(10, b)); } }
Implementation, Min. There is no magic in the implementation of these methods. We examine the implementation of Math.Min in the base class library.

Internals: The Math.Min overload for Int32 returns the result of an if-conditional.

However: I found that the Math.Min methods for decimal and float contain additional processing only for those types.

Internal implementation of Min: C# [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int Min(int val1, int val2) { if (val1 > val2) { return val2; } return val1; }
A discussion. You will need to test again zero many times. Using a negative number on an indexer will throw an exception (an IndexOutOfRangeException).IndexOutOfRangeException

Performance: I have benchmarked Math.Min and Math.Max and they are no different from typing the logic yourself.

And: The only difference is that your code is shorter, simpler to read, and less prone to typos.

Max extension. There are Max and Min extension methods in the System.Linq namespace. These are called on IEnumerable collections, and are different from Math.Max and Math.Min.Max, Min
A summary. We clarified bounds-checking with Math.Min and Math.Max. These methods transform imperative code to declarative code—they improve important algorithms.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls