Solved

The as operator

Posted on 2004-04-07
12
257 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
 
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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

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 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…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

706 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now