Solved

The as operator

Posted on 2004-04-07
12
260 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 50 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 50 total points
ID: 10774139
var
  b: TMemo;
begin
  (b as TLabel).Caption;        // compilation error
  TLabel(b).Caption;             // compilation OK
0
ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

 
LVL 17

Assisted Solution

by:geobul
geobul earned 50 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 50 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

ScreenConnect 6.0 Free Trial

Discover new time-saving features in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Delphi application Soap connection 5 105
Create Database on Android via Delphi dbExpress 3 94
update joined tables 2 47
Delphi Seattle StructureView color 1 5
The uses clause is one of those things that just tends to grow and grow. Most of the time this is in the main form, as it's from this form that all others are called. If you have a big application (including many forms), the uses clause in the in…
In this tutorial I will show you how to use the Windows Speech API in Delphi. I will only cover basic functions such as text to speech and controlling the speed of the speech. SAPI Installation First you need to install the SAPI type library, th…
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

832 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