Caché Basic Reference
[Home] [Back] [Next]
InterSystems: The power behind what matters   
Class Reference   

Compares a target to cases and returns the value associated with the first matching case.
target A value, variable, or expression to be compared with the case arguments.
case A value, variable, or expression, the value of which is matched with the value of target.
rvalue The value to be returned upon a successful match of target and case.
default Optional — The value to be returned if no case matches target.
The Case function compares target to a list of cases (literals or expressions), and returns the rvalue associated with the first matching case value. An unlimited number of case:rvalue pairs can be specified. Cases are matched in the order specified (left-to-right); matching stops when the first exact match is encountered.
If there is no matching case, the default is returned. If there is no matching case and no default is specified, an error is returned.
CASE evaluates the target expression once, then matches the result to each case value in left-to-right order.
A case can be a literal or an expression; matching of literals is substantially more efficient than matching expressions, because literals can be evaluated at compile time. Each case must be paired with an rvalue. An unlimited number of case and rvalue pairs may be specified.
An rvalue can be a literal or an expression. Every rvalue is associated with a specific case as a pair joined with a colon (:) and separated from other pairs by a comma (,). rvalue is the value returned when there is an exact match of the target value with its associated case value. Only the first exact match encountered (in left-to-right order) returns an rvalue.
A default argument can be a literal or an expression. The default is specified like a case:rvalue pair, except that there is no case specified between the comma separator and the colon. The default is always the final argument specified in a CASE function. The default value is the value returned if no exact match occurs.
The following Case example takes a numeric input and writes out the appropriate explanatory string:
input "Input a number 1-3: ",x
multi=CASE(x,1:"single",2:"double",3:"triple",:"input error")
PrintLn multi
See Also