With a Case statement, you can control the flow of your program based on the values of certain parameters or variables. For example, you want to multiply the price of a security by two if the parameter multiply is set to Twice, but divide it by two if the parameter is set to Half.

Tip                 Enumeration types (see Enumerations) are especially useful for Case statements, as they limit the possible values that a variable or parameter can hold.

Case statements can almost always be substituted by several If statements. However, they usually offer a better overview of the different available options and their results.

Syntax

Case VarOrParam Of
   Value1: Statement1;
   Value2, Value3, ...: Statement2;
   ...
Else
   Statement3
End;

Case

Starts the Case statement

VarOrParam

Name of the variable or parameter that should control the flow of the program.

Of

Reserved word

Value1

Value2

Value3

Possible constant values of the controlling variable or parameter. You can use enumerators, positive numbers, text or Boolean values.

If you want to link a statement to more than one possible value, separate the values with a comma.

Statement1

Statement2

Any command statement or block statement that should be executed when the controlling variable or parameter holds the corresponding value.

Else

Starts the Else execution block: This block is executed only if the controlling variable or parameter holds a value not listed in the Case statement part above. This part is optional.

Statement3

Any command statement or block statement that will be executed when no matching value is found in the above list. Don't put a semicolon at the end of this statement.

End

Ends the case statement.

Examples

In the following example, the parameter multiply is used to control the output of the program: Depending on its value, the example indicator will show the triple, double or half Close prices of the base security as a line. To ensure that no other values than the ones used in the Case statement can be assigned to the parameter, the enumeration type Mode has been created for this parameter.

Function CaseExample
Returns Nothing;

Enum
Mode = (Normal, Double, Triple, Half);

Parameters
   Security Source;
   Mode multiply;

Variable
   Numeric price;

Begin

   Case multiply Of
          Triple: price = Source * 3;
         
Double: price = Source * 2;
          Half: price = Source / 2;
  
Else
         
price = Source
  
End;

   DrawLine("SampleLine", price);

End.

The section on enumeration types shows a very similar example using If statements instead.