Solved

The as operator

Posted on 2004-04-07
12
259 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
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…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…

920 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

16 Experts available now in Live!

Get 1:1 Help Now