Instead of using a bunch of complex nested if statements, you can use a case statement to provide a more readable alternative so long as the conditionals return an integer.
Case Syntax:
case selectorExpression of
caseList1: statement1;
...
caseListx: statementx;
end
The selectorExpression is any expression of an ordinal type. This can be a number like 1, 2, 3, etc., an expression that evaluates to an ordinal, or a constant (like Red, White, and Blue). Unfortunately string types are not valid. (ObjectPAL programmers will note that ObjectPAL's switch statement is much more powerful and easier to use.)
Here is a simple example of using a case statement.
// Set x to 1, 2, 3, then 4 to see what
// message is displayed.
procedure TForm1.Button2Click(Sender: TObject);
var
lbValue: Byte; // Local byte (lb).
begin
lbValue := 3;
case lbValue of
1: ShowMessage('one');
2: ShowMessage('two');
3: ShowMessage('three');
else
ShowMessage('special');
end;
end;
Using Case and MessageBox
In this next example, we use the fact that MessageBox returns an integer. What integer it returns is based on what button the user chooses. Refer to the code below for integer values:
procedure TForm1.Button3Click(Sender: TObject);
var
liAns: Integer; // Local integer (li).
begin
liAns := Application.MessageBox('Are you a Delphi fan?',
'Yes or No?', MB_YesNoCancel);
case liAns of
2: ShowMessage('You chose Cancel');
6: ShowMessage('You chose Yes.');
7: ShowMessage('You chose No.');
end;
end;
A case statement is a programming language command that can be used in Object PASCAL to select which subroutine should execute top writing services, based on the value of one or more expressions. Case statements are often used when writing nested loops and if/then/else clauses. The operator "case" selects which branch will execute depending on the value of an expression.