Math.Max and Math.Min Examples
This page was last reviewed on Feb 19, 2023.
Dot Net Perls
Math.Max, Min. Math.Max returns the larger value. It can improve C# code that calculates integer bounds. Min() does the same thing, but returns the lower value.
Method info. Often in C# programs we need to test if an integer is less than zero. We use Math.Max to test for these conditions with less code.
Math.Max example. This method returns the higher of the 2 arguments. It can make your code more maintainable—you can rewrite if-statements to code that calls Math.Max or Min.
Version 1 This version of the code uses Math.Max—it prints the greater of the 2 arguments. It may be easier to read.
Version 2 Here we use an if-statement to determine which of the two values is bigger. Notice how it uses more lines of code.
using System; class Program { static void Main() { // Version 1: get the bigger value with Math.Max. int a = 4; Console.WriteLine(Math.Max(0, a)); // Version 2: get the bigger value with if. int result = a; if (0 > a) { result = 0; } else { result = a; } Console.WriteLine(result); } }
4 4
Bounds check. We use the Math.Max method to check bounds. You can replace many if-statements with one line of code using Math.Max.
And We take the maximum of zero and the value. The result will never be less than zero.
Info GetLastIndex() internally uses the Math.Max function. It returns one index from the last index.
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.
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]; } }
6 2 1
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, uint
Detail 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.
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); } }
4 -1000
Implementation, Min. There is no magic in the implementation of these methods. We examine the implementation of Math.Min in the base class library.
Detail 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.
[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).
Detail I have benchmarked Math.Min and Math.Max. Their performance is no different from specifying the logic yourself.
Info 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
Ternary. A discussion of Math.Max and Min would be incomplete without a method of the ternary statement. A ternary is an if-statement used in assignments.
A summary. We used Math.Min and Max for simple numeric comparisons. These methods transform imperative (statement-based) C# code to declarative code.
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 Feb 19, 2023 (edit).
© 2007-2024 Sam Allen.