Selection Functions  

 

Versions

This section covers the Switch, IIf, and Choose functions.

 


Switch

  • Function Switch is related to the If/Then/Else structure.

  • Each argument passed to Switch is either a condition or a value.

  • Any number of condition-value pairs can be passed to Switch.

  • If a condition is True, the value associated with that condition is returned.

  • If no condition is True, Switch returns Null.

  • Function Switch does not provide Else functionality; a value must be paired with a condition. For example, the assignment

      lblStudentGrade.Text = Microsoft.VisualBasic.Switch(grade >= 90, "A",  _
                                                                                          grade >= 80, "B",  _
                                                                                          grade >= 70, "C",  _
                                                                                          grade >= 60, "D",  _
                                                                                          grade < 60, "F")


IIf

Visual Basic provides the function IIf, which is closely related to the If/Then/Else structure. Function IIf takes three arguments-the condition, the value returned when the condition is True and the value returned when the condition is False.

Example: lblStatus.Text = IIf(grade >= 60, "Passed", "Failed")


Choose

Function Choose is related to the Select Case statement.

  • The first argument is an Integer that specifies the index of any argument after the first argument.

  • Any number of items (of any type) can be provided after the first argument.

  • Index values start at 1.

  • Example: Print Choose(someVar, "Red", "Green", "Blue") 

    • prints either Red, Green or Blue depending on the value of someVar

    • If someVar is 1, Red is displayed. 

    • If someVar is 2, Green is displayed.

    • If someVar is 3, Blue is displayed.

  • Choose returns Null if someVar has a value that is not between 1 and 3 inclusive.

  • If a floating-point number is passed as the first argument, it is rounded to the nearest Integer.