Examples of the as Clause Expression

The following is an example of an explicit type name being used to down-cast the target variables type. As long as the collection contains only Fruit instances, the foreach instruction executes without compile‑time or runtime exceptions.

iterateFruit(collection: Collection);
vars
    fruit: Fruit;
begin
    foreach fruit in collection as Fruit do
        fruit.eat();
    endforeach;
end;

This method could be provided with a collection with a membership type of Fruit (or a subclass of Fruit), or a collection with a membership type that is a super-type of Fruit but contains only Fruit instances.

The following is an example of a method that causes a 6460 exception when compiled, because the as clause type is not a sub-type of the collection membership.

exceptionExample_6460(fruitCollection: FruitArray);
vars
    animal: Animal;
begin
    // The following line will not compile as Animal is not a subclass of Fruit.
    foreach animal in fruitCollection as Animal do
        animal.pat();
    endforeach;
end;

The following is an example of a method that would cause a 6072 exception when compiled, as the target variable is not the same or a super-type of the as clause type.

exceptionExample_6072(collection: Collection);
vars
    animal: Animal;
begin
    /* The following line will not compile because Animal and Fruit 
    are incompatible types.*/
    foreach animal in collection as Fruit do
        animal.pat();
    endforeach;
end;

2020.0.01 and higher