Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

The as operator

Posted on 2004-04-07
12
Medium Priority
?
269 Views
Last Modified: 2010-04-05
I frequently use the is operator but never the as operator and wonder what it is good for. Everything can be done with a simple cast...

procedure Foo(o: TObject);
begin
  if o is TMyObject then
    TMyObject(o).DoStuff;
  ...
end;

Opinions?
0
Comment
Question by:__alex
  • 4
  • 4
  • 2
  • +2
12 Comments
 
LVL 27

Assisted Solution

by:kretzschmar
kretzschmar earned 200 total points
ID: 10774079
the as operator performes a safe typecast,
whereas
TMyObject(o)
is a hard unchecked typecast

see delphi online help

usual i myself use as not often

meikl ;-)
0
 
LVL 27

Expert Comment

by:kretzschmar
ID: 10774096
from delphi help:

The as operator performs checked typecasts. The expression

object as class

returns a reference to the same object as object, but with the type given by class. At runtime, object must be an instance of the class denoted by class or one of its descendants, or be nil; otherwise an exception is raised. If the declared type of object is unrelated to class
--that is, if the types are distinct and one is not an ancestor of the other--a compilation error results.

meikl ;-)
0
 
LVL 17

Assisted Solution

by:mokule
mokule earned 200 total points
ID: 10774139
var
  b: TMemo;
begin
  (b as TLabel).Caption;        // compilation error
  TLabel(b).Caption;             // compilation OK
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 17

Assisted Solution

by:geobul
geobul earned 200 total points
ID: 10774220
It should be:

procedure Foo(o: TObject);
begin
  if (o is TMyObject) then
    (o as TMyObject).DoStuff;
  ...
end;

Regards, Geo
0
 
LVL 2

Author Comment

by:__alex
ID: 10774322
@kretzschmar
Why check things twice:
if o is TMyObject then             // First check
  (o as TMyObject).DoStuff;     // Second check ???

@mokule
Good point but...
if you know b is a memo, why do you want to set its caption?
If you don't know what b is it's better to check it or an exception might be raised:
  if b is TLabel then TLabel(b).Caption := foo;

Still can't think of any (real) use of the as
0
 
LVL 2

Author Comment

by:__alex
ID: 10774327
@geobul -> @kretzschmar
0
 
LVL 27

Expert Comment

by:kretzschmar
ID: 10774373
:-)) see my first comment,

this is the difference,
the compiler developers cannot know,
if you check it before with the is-operater,
thats why the as-operator is introduced
0
 
LVL 2

Author Comment

by:__alex
ID: 10774509
@kretzschmar
Ok, now I get your point, thanks!
0
 
LVL 27

Expert Comment

by:kretzschmar
ID: 10774584
maybe this illustrates the difference,
watch about the different exceptions u get

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    ComboBox1: TComboBox;
    ComboBox2: TComboBox;
    procedure AsTypeCastClick(Sender: TObject);
    procedure HardTypeCastClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure ShowItems(AComboBox : TComboBox);
begin
  if assigned(AComboBox) then
    ShowMessage(AComboBox.Items.Text);
end;

//is assigned to Button1 and ComboBox1 onClick-event
procedure TForm1.AsTypeCastClick(Sender: TObject);
begin
  ShowItems(sender as TComboBox);
end;

//is assigned to Button2 and ComboBox2 onClick-event
procedure TForm1.HardTypeCastClick(Sender: TObject);
begin
  ShowItems(TComboBox(sender));
end;

end.

meikl ;-)
0
 
LVL 17

Expert Comment

by:geobul
ID: 10774738
>(o as TMyObject).DoStuff;     // Second check ???

It's not a check but typecast
0
 
LVL 26

Accepted Solution

by:
Russell Libby earned 200 total points
ID: 10775843
Something from the Borland website that I have found useful in the past

function IsAs(out ObjRef; Obj: TObject; ObjClass: TClass): Boolean;
begin

  // Determine if the the object passed in is of the desired class
  result:=Assigned(Obj) and (Obj is ObjClass);

  // Set result is successful
  if result then
     // Set out going object reference
     TObject(ObjRef):=Obj
  else
     // Set out going object reference to nil
     TObject(ObjRef):=nil;

end;

Example usage:

procedure TForm1.ComboBox1Change(Sender: TObject);
var  obj:        TComboBox;
begin

 if IsAs(obj, Sender, TComboBox) then obj.Text:='Hello world';

end;

-------------

Russell

0
 
LVL 2

Author Comment

by:__alex
ID: 10781572
Very nice! It makes the code look pretty...
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to…
In my programming career I have only very rarely run into situations where operator overloading would be of any use in my work.  Normally those situations involved math with either overly large numbers (hundreds of thousands of digits or accuracy re…
Screencast - Getting to Know the Pipeline
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses
Course of the Month20 days, 15 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question