VB.NET Math.Max and Math.Min

Math written on chalkboard

How can you use the Math.Max and Math.Min functions in your VB.NET program to find the largest and smallest values in your data? We provide an example that searches an array in a single pass for the smallest and largest elements with these useful but simple functions.

Example

Note

This program first creates 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.

This VB example program shows how to use the Math.Max and Math.Min Functions.

Program that uses Math.Max and Math.Min [VB.NET]

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
Foreach loop construct

For Each loop description. In the For Each loop, we continually assign largest and smallest. You can call Math.Max and Math.Min with any two integers: if you use the integer you are assigning as an argument, the Integer variable will only increase (for Max) or decrease (for Min). The results are correct, as we can see in the output.

Performance

Performance optimization

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 VB.NET programming language

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. If other statements must be used, however, the if-statement is better because fewer branches will be required if you only use one selection statement.

VB.NET Tutorials
.NET