as
The As keyword is used for casting objects or interfaces of one type to another. Casting allows an object to be
referenced by a parent class type. For example, all objects may be referred to as a TObject class type:
button1 := Button1 As TObject;
If the object has already been cast to a parent class type, then casting to a valid child class type is allowed. Use the Is keyword to check for castability before attemting a cast. Invalid casting gives EInvalidCast when you try to use the cast value.
Example
Download This Source for Free Pascal
{$MODE DELPHI} // Support "Class"
uses
Classes; // so we have something to refer to
type
myStringList= class(TStringList)
public
procedure WriteLnList;
end;
var
myByte : Byte;
myChar : Char;
StrList1: TStringList;
StrList2: myStringList;
procedure myStringList.WriteLnList;
Var
Loop:Integer;
begin
For Loop:=0 to Count-1 do
Writeln(Loop,' contains ',Self[Loop]);
end;
begin
myByte := 65;
// Cast this Byte to Char using the standard casting method
myChar := Char(myByte);
Writeln('myByte standard casting to Char = ',myChar);
StrList1 := TStringList.Create;
StrList1.Add('Apple');
StrList1.Add('Banana');
StrList1.Add('Orange');
// Standard casting does not check if we change classes:
myStringList(StrList1).WritelnList;
// Casting using 'as' rejects the invalid casting
StrList2 := StrList1 as myStringList;
// The following yields the EInvalidCast error
StrList2.WritelnList;
StrList1.Free;
end.
Output
myByte standard casting to Char = A
0 contains Apple
1 contains Banana
2 contains Orange
An unhandled exception occurred at $08048263 :
EInvalidCast : Invalid type cast
See Also
Is.