Conditional Operator

Evaluates one of two or three expressions based on a condition.

Syntax

Two-way form
If condition Then trueValue Else falseValue
Three-way form
If expression1 To expression2 { Is comparisonOp valueN }...

Parts

condition
A Boolean expression
trueValue
falseValue
expression1
An expression of a data type that permits comparisons.
expression2
An expression of a data type compatible with expression1.
comparisonOp
Comes after the Is keyword.
valueN
One of two or three expressions evaluated only when the associated comparisonOp makes a true comparison between expression1 and expression2.

Details

Two-way form

The two-way form closely resembles the If...Then...Else statement, except the operator evaluates expressions rather than statements.

When condition evaluates to true, trueValue is evaluated and its value is the result of the operation—falseValue is not evaluated. When condition evaluates to false, falseValue is evaluated and its value is the result of the operation—trueValue is not evaluated.

Normally, trueValue and falseValue must be compatible data types. One exception is when the enclosing expression can accept more than one data type, such as a polymorphic method.

Three-way form

The three-way form offers a compact and efficient way to compare two expressions and return different values depending on how they compare. This form of the operator slightly resembles the semantics of the Select...Case statement.

This form requires the use of the <, =, and > comparison operators, either separately or combined as <=, >=, or <>. When used separately, the expression must have three Is clauses with three result values When you combine two comparisons, the expression then permits only two Is clauses with two result values.

Examples

Function FootOrFeet(dist As Real) As String
    Return If dist = 1.0 Then "foot" Else "feet"
End Function

Function Polarity(x As Real) As String
    Return If x To 0.0 Is < "negative" Is = "neutral" Is > "positive"
End Function

Function FootOrFeet(dist As Real) As String
    Return If dist To 1.0 Is = "foot" Is <> "feet"
End Function

See also