As
Belongs to : KeywordDescription
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.
Example code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
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; { 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' } |