DelphiBasics
As
Keyword
Used for casting object references
1 keyword As(Object reference as Class type
2 Object reference | Interface reference as Interface type
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
IsTests whether an object is a certain class or ascendant
 Download this web site as a Windows program.




 
Example code : Casting using traditional and as casting
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;
Show 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'
 
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page