FreePascal Information Logo Friend of FreePascal Compiler Title
Articles with Feedback, FPC News Library, PDF Collection, Mail Lists, Books, Newsgroups, IRC Open online discussion areas Research and Tutorials Tools, Compilers and Utilities Blurbs about us, advertising, etc.
Welcome to the FoFPC Pascal Language AS

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 Source IconDownload 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.
 Links and Products we find useful



ButtonGenerator.com
Valid XHTML 1.0 Transitional Internet Map
Programmer's Heaven
grat-i-fi-ca-tion - noun
the state of being gratified; great satisfaction.


I am very happy to see that FoFPC is alive, we need more developers working on this great language.
Matias Vara
toro.sourceforge.net
Locations of visitors to this page world map hits counter
Copyright 2009 by 3F, LLC. All rights reserved. Worldwide.
Your request was processed by server #2 in 0.003290 secs.

sponsor
Click to visit our paid sponsor