Show/Hide Toolbars

XSharp

Purpose

Conditionally execute a block of statements.

Syntax

SWITCH <expression>
CASE <constantvalue> [WHEN <whenexpression>]
  <Statements>...
[CASE <constantvalue>]
[CASE <constantvalue>]
  <Statements>...
[CASE <constantvalue>]
  <Statements>...
[CASE <variablename> AS <datatype>] [WHEN <whenexpression>]
  <Statements>...
[OTHERWISE]
  <Statements>...
END [SWITCH]

Arguments

<constantvalue>A constant value that can be evaluated at compile time. You can also have 2 consecutive CASE lines without statements between them. In that case both CASE lines share the same statementblock. If you want a case block without statements, then insert a NOP statement as its statement.
<whenexpression>A logical expression that determines if the particular CASE block should be active This is sometimes called an expression filter.
<variablename>A variablename that gets declared by the pattern matching expression
<datatype>The datatype of the variable in the pattern matching expression

 

OTHERWISEIf none of the preceding CASE conditions match, the statements following the OTHERWISE up until the next END SWITCH are executed. Afterwards, control branches to the statement following the next END SWITCH statement.

Description

SWITCH works by branching to the statement following the first CASE <constantvalue> that evaluates to TRUE. If all CASE conditions evaluate to FALSE, it branches to the statement following the OTHERWISE statement (if specified).

In general there are 2 types of SWITCH statements:

1.Switch statements with constant values (CASE <constantvalue>)

2.Switch statements with pattern matching expressions (CASE <varName> AS <datatype>)

Both types of SWITCH statements can be enhanced with WHEN filters.

If you do not have a WHEN filter then each CASE line must be "unique", so no two CASEs can have the same constantvalue or same datatype. If you add a WHEN filter then this is allowed.

The compiler may (and will) rearrange the order of the CASE labels when generating code for example to combine two CASEs with the same constant value and a WHEN filter. These may be combined into one CASE label with an embedded IF statement.

 

Execution proceeds until the next CASE, OTHERWISE, or END SWITCH is encountered, and control then branches to the first statement following the next ENDCASE statement.

Control structures can be nested to any depth. The only requirement is that each control structure be properly nested.

 

Examples

This example uses SWITCH in a menu structure to branch control based on user selection:

FUNCTION ActonChoice(nChoice as LONG) AS VOID
SWITCH nChoice
CASE  0
  RETURN
CASE 1
  ChoiceOne()
CASE 2
  ChoiceTwo()
END SWITCH

See Also

BEGIN SEQUENCE, DO WHILE, FOR, FOREACH IF DO CASE