Description |
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. The sample code shows this for the TForm class object when it is passed as a TObject type to the OnCreate method of the form.
|
|
Notes |
Use the Is keyword to check for castability before attemting a cast.
Invalid casting gives EInvalidCast when you try to use the cast value.
|
|
Related commands |
Is |
|
Tests whether an object is a certain class or ascendant |
|
|
|
Example code : Casting using traditional and as casting |
// Full Unit code. // ----------------------------------------------------------- // You must store this code in a unit called Unit1 with a form // called Form1 that has an OnCreate event called FormCreate. unit Unit1; interface uses Forms, Dialogs; type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} // Include form definitions procedure TForm1.FormCreate(Sender: TObject); var
myForm : TForm;
myForm1 : TForm1;
myByte : Byte;
myChar : Char;
begin
myByte := 65;
// Cast this Byte to Char using the standard casting method
myChar := Char(myByte);
ShowMessage('myByte standard casting to Char = '+myChar);
// Cast the Form to myForm using standard casting
myForm := TForm1(Sender);
ShowMessage('Sender using standard casting = '+myForm.Caption);
// Cast the form using the as keyword
myForm := Sender As TForm;
ShowMessage('Sender as valid child = '+myForm.Caption);
myForm := Sender As TForm1;
ShowMessage('Sender as itself = '+myForm.Caption);
// Create a new TForm object rather than TForm1
myForm := TForm.Create(self);
myForm.Caption := 'New form';
// Standard casting does no checking if we cast TForm to TForm1
myForm1 := TForm1(myForm);
ShowMessage('Standard casting to bad child = '+myForm1.Caption);
// Casting using 'as' rejects object to invalid child casting
myForm1 := myForm As TForm1; // The following yields the EInvalidCast error
ShowMessage('As casting to bad type = '+myForm1.Caption);
end; end.
|
Hide full unit code |
myByte standard casting to Char = A
Sender using standard casting = Form1
Sender as valid child = Form1
Sender as itself = Form1
Standard casting to bad child = New form
EInvalidCast error : 'Invalid cast type'
|
|