Name
As Keyword
Syntax
Object referenceasClass typeObject or interface referenceasInterface type
Description
The
as operator converts an object reference to a
different class type or converts an interface reference to a
different interface type. The type of the expression is the class or
interface type on the right-hand side of the as
operator.
Tips and Tricks
If the object or interface reference is
nil, the result isnil.The object’s declared class must be a descendant or ancestor of the class type. If the object reference is not of a compatible type, the compiler issues an error. If the declared type is compatible, but the object’s true type at runtime is not the class type or a descendant type, Delphi raises runtime error 10 (
EInvalidCast).You should use the
asoperator instead of a type cast when typecasting an object reference. The only exception is when you know the type from an earlier use of theisoperator.If the desired type is an interface, Delphi calls the
QueryInterfacemethod, passing the interface type’s GUID as the first argument. If the object does not implement the interface, Delphi raises runtime error 23 (EIntfCastError).
Example
// When any check box is checked, enable the OK button.
// This event handler can be used for multiple check boxes.
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
if (Sender as TCheckBox).Checked then
OkButton.Enabled := True;
end;See Also
| Interface Keyword, Is Keyword, TObject Type |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access