Visual Basic Language Reference  

Switch Function

Evaluates a list of expressions and returns an Object value of an expression associated with the first expression in the list that is True.

Public Function Switch( _
   ByVal ParamArray VarExpr() As Object _
) As Object

Parameter

VarExpr()
Required. Object parameter array. Must have an even number of elements. You can supply a list of Object variables or expressions separated by commas, or a single-dimensional array of Object elements.

Exceptions/Errors

Exception type Error number Condition
ArgumentException 5 Number of arguments is odd.

Remarks

The Switch function argument VarExpr consists of paired expressions and values. The Switch function evaluates the expressions from lowest to highest subscript in VarExpr, and returns the value associated with the first expression that evaluates to True. For example, if VarExpr(0) is True, Switch returns VarExpr(1), and if VarExpr(0) is False but VarExpr(2) is True, Switch returns VarExpr(3), and so on.

If you do not supply the VarExpr argument, Switch returns Nothing. If the number of elements in VarExpr is not divisible by two, an ArgumentException error occurs.

Note   The expressions in the argument list can include function calls. As part of preparing the argument list for the call to Switch, the Visual Basic compiler calls every function in every expression. This means that you cannot rely on a particular function not being called if an expression earlier in the argument list is True.

Example

This example uses the Switch function to return the name of a language that matches the name of a city. It requires that Option Strict be Off.

Function MatchUp (CityName As String) As String
   Return Microsoft.VisualBasic.Switch(CityName = "London", "English", _
      CityName = "Rome", "Italian", CityName = "Paris", "French")
End Function

Since the System.Diagnostics namespace contains a class called Switch, a call to the Switch function must be qualified with the Microsoft.VisualBasic namespace.

See Also

Choose Function | IIf Function | Select...Case Statements | Switch Class