VB.NET Math.Max and Math.Min

Use the Math.Max and Math.Min Functions to compare arguments and get the larger or smaller one.

Math.Max, Math.Min. These functions find the largest, and smallest, values in the data. We provide an example. It searches an array in a single pass for the smallest and largest elements. It uses these useful but simple functions.

Example. We create an array of seven integer values upon the managed heap. Next we initialize the largest and smallest Integer variables. We set them to Integer.MinValue and Integer.MaxValue so that they will be reassigned as the loop iterates.Integer

For-Each: Here we continually assign largest and smallest. You can call Max and Min with any two integers.

For Each, For

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 Module Output 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. With a single pass, we must read the elements in the array half as many times.

Summary. The Math.Max and Math.Min functions are a declarative way of writing an if-statement that tests the two values against each other. Because they result in shorter code, they are often preferable.

However: If other statements must be used, the if-statement is better because fewer branches are required with one selection statement.

Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to