Conditional Operator

Selects one expression to calculate, given two or more expressions, because of a condition.

Syntax

Boolean construct

``````If condition Then then_result Else else_result
``````

Comparison construct

``````If expression_1 <=> expression_2 { ( [ Is ] comparison_op ) result_n }…
``````

Parts

`condition`
A Boolean expression
`then_result`
An expression. When `condition` is true, it becomes the result of the conditional expression.
`else_result`
An expression.
Mandatory in the Boolean construct. When `condition` is false, it becomes the result of the conditional expression.
`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 a left parenthesis and optionally `Is`.
`result_n`
One of two or more expressions evaluated only when the related `comparison_op` makes a true comparison between `expression_1` and `expression_2`.

Instructions

Boolean construct

The Boolean construct closely resembles the statement `If…Then…Else`. But the operator evaluates expressions, not statements.

When `condition` evaluates as true, `then_result` is evaluated and its value is the result of the operation—`else_result` is not evaluated. When `condition` evaluates as false, `else_result` is evaluated and its value is the result of the operation—`then_result` is not evaluated.

Usually, `then_result` and `else_result` must be compatible data types. But they can be different types if, for example, the outer expression can accept more than one data type, such as a polymorphic method.

Comparison construct

The comparison construct lets you compare two values, and returns a different value given how they compare. This construct can look like the statement `Select…Case`.

This construct requires the use of the comparison operators `<`, `=`, and `>`. You can use all three, or you can put them together as `<=`, `>=`, or `<>`.

With all three comparisons, the expression must have three `Is` clauses with three result values. With only two comparisons, the expression then permits only two `Is` clauses with two result values.

Usually the data types of the result expressions must be compatible. But they can be different types if, for example, the outer expression can accept more than one data type, such as a polymorphic method.

Examples

Boolean construct

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

Comparison construct

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

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