VB.NET Math.Max and Math.MinUse the Math.Max and Math.Min Functions to compare arguments and get the larger or smaller one.

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.

VB.NET program that uses Math.Max with 2 arguments

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

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.

Tip If you use the integer you are assigning as an argument, the Integer variable will only increase (for Max) or decrease (for Min).

VB.NET program that uses Math.Max and Math.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

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.