Conditional Operator

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

Syntax

Two-way form

If condition Then true_value Else false_value

Three-way form

If expression_1 To expression_2 { Is comparison_op value_n }...

Parts

condition
A Boolean expression
true_value
false_value
expression_1
An expression of a data type that permits comparisons.
expression_2
An expression of a data type compatible with expression_1.
comparison_op
Comes after the Is keyword.
value_n
One of two or three expressions evaluated only when the associated comparison_op makes a true comparison between expression_1 and expression_2.

Instructions

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, true_value is evaluated and its value is the result of the operation—false_value is not evaluated. When condition evaluates to false, false_value is evaluated and its value is the result of the operation—true_value is not evaluated.

Normally, true_value and false_value 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