AS
Previous  Top  Next

The as operator performs checked typecasts. The expression

object as class

returns a reference to the same object as object, but with the type given by class. At runtime, object must be an instance of the class denoted by class or one of its descendants, or be nil
; otherwise an exception is raised. If the declared type of object is unrelated to class—that is, if the types are distinct and one is not an ancestor of the other—a compilation error results. For example,

with Sender as TButton do

begin
Caption := '&Ok';
OnClick := OkClick;
end;

The rules of operator precedence often require as typecasts to be enclosed in parentheses. For example,

(Sender as TButton).Caption := '&Ok';