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.
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.
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 ModuleMAX: 200
In this example we create an array of 7 integer values. Next we initialize the largest and smallest Integer variables.
Integer.MinValue
and Integer.MaxValue
so that they will be reassigned as the loop iterates.Max
and Min
with any two integers.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 Module200 -100
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.
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.