Visual Basic - MinValue and MaxValue Properties

Today I was asked by a friend who is studying Visual Basic to write an article on the properties MinValue and MaxValue at first I thought these very simple properties were hardly worth an article but then I realised that when just starting out in programming it’s good to have examples of when these properties, could or should be used.

If we wanted to collect 10 scores of student’s exams results and then display the minimum and maximum score entered we could do so with the following code.

      
Dim min = 101, max = 101, score As Integer = 0

        For i As Integer = 1 To 10
            score = InputBox("Enter student Grade", "Enter Grade", 0)

            If score < min Then
                min = score
            End If

            If score > max Then
                max = score
            End If
        Next

        MessageBox.Show("Minimum Score " & min & vbNewLine & _
                "Maximum Score " & max, "Results", MessageBoxButtons.OK, MessageBoxIcon.Information)

We have declared our variables, min, max and score and initialised the min and max variables to 101. Inside the For loop we ask for a score to be entered and then decide if the score entered was less than the minimum score and greater than the max score if so we assign the new values accordingly.

This will work as long as our score results are always less than a 100, but what if we want to give our program to other people to use where we will not know the highest or lowest scores that will be entered.

Dim min = Integer.MaxValue, max = Integer.MinValue, score As Integer = 0

        For i As Integer = 1 To 10
            score = InputBox("Enter student Grade", "Enter Grade", 0)

            If score < min Then
                min = score
            End If

            If score > max Then
                max = score
            End If
        Next

        MessageBox.Show("Minimum Score " & min & vbNewLine & _
                "Maximum Score " & max, "Results", MessageBoxButtons.OK, MessageBoxIcon.Information)

Setting the min and max variables to the Integer.MaxValue and Integer.MinValue will assure that our If statement will always evaluate to true for the first iteration of the loop, setting our min and max score variables.

MaxValue and MinValue will initialise the variable with the largest possible number for the data type they follow. MaxValue and MinValue can be used with all numeric data types so go ahead and try them out.

Note: This is only a very simple example will no validation added.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.