Home
VB.NET
Math.Max and Math.Min
Updated 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.
Integer
Detail Here we continually assign largest and smallest. You can call Max and Min with any two integers.
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).
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 5, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen