Math.Max and Math.Min
This page was last reviewed on Dec 5, 2023.
Dot Net Perls
Math.Max, Math.Min. These VB.NET functions find the largest, and smallest, values when passed 2 values. Max() and Min are function calls that contain if-statements.
Function usage. By calling Math.Max and Math.Min in a loop, we can search an array for the smallest and largest elements. Constants like Integer.MaxValue are also helpful.
Simple example. First we show a simple use of Math.Max. The Math.Min function can be used in the same way—try changing Math.Max to Math.Min in this code.
Module Module1 Sub Main() Dim value1 = 100 Dim value2 = 200 ' Compare the 2 values. Dim max = Math.Max(value1, value2) Console.WriteLine("MAX: {0}", max) End Sub End Module
MAX: 200
Complex example. In this example we create an array of 7 integer values. Next we initialize the largest and smallest Integer variables.
Note We set them to Integer.MinValue and Integer.MaxValue so that they will be reassigned as the loop iterates.
Detail Here we continually assign largest and smallest. You can call Max and Min with any two integers.
Tip If you use the integer you are assigning as an argument, the Integer variable will only increase (for Max) or decrease (for Min).
Module Module1 Sub Main() ' Find largest and smallest elements in array. Dim vals As Integer() = {1, 4, 100, -100, 200, 4, 6} Dim largest As Integer = Integer.MinValue Dim smallest As Integer = Integer.MaxValue For Each element As Integer In vals largest = Math.Max(largest, element) smallest = Math.Min(smallest, element) Next Console.WriteLine(largest) Console.WriteLine(smallest) End Sub End Module
200 -100
Performance. There are other ways to determine the maximum and minimum values in an array of Integers. But some of these would require two separate passes through the array.
Info With a single pass, we must read the elements in the array half as many times. This is important for efficiency.
A summary. The Math.Max and Math.Min functions are a declarative way of testing the 2 values against each other. Because they result in shorter code, they are often preferable.
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 Dec 5, 2023 (edit).
© 2007-2024 Sam Allen.