Case Statements

The case statement splits code flow, and executes one (or none) of several optional code paths, based on the value of the provided expression:

case value of
  1: writeLn('One');
  2: writeLn('Two');
  6..9: writeLn('Between six and nine')
  else writeLn($'Unexpected value: {value}');
end;

The expression provided between case and of can be of any type that can be compared to constant or literal values, including numbers or strings. The expression will be evaluated once, and the case that matches its value will be executed. If no case matches, and an optional else clause is provided, it will execute.

Each case statement must be unique, and having duplicate or overlapping statement ranges will cause a compiler error. Each case can either specify a single value, or a range of values that the expression must fall within, for the case to match.

begin/end blocks can be used in order to provide more than one statement for an individual case, or for the else clause.

Unlike other languages, execution will not "fall though" from the first matching case to others, but only a single case will ever be executed.

Case type of

A variation is the case type/of statement, which allows you to execute different cases depending on the type of the expression at runtime:

case myControl type of
  Button: writeln("Looks like a button!");
  CheckBox: writeln("This one's a checkbox");
  else writeLn("No idea what this is!?");   
end;

Essentially, a is cast is performed on each case, and the first matching case will be executed. Note that unlike for regular case/of, this construct allows for potential overlap (e.g. for descendent types), so attention must be paid that the case for a base type does not prevent a later case for a more concrete subtype to ever be hit.

See Also