Board index » delphi » "TButton(Sender)" and "(Sender as TButton)"

"TButton(Sender)" and "(Sender as TButton)"

Quote
dr...@thjzgn.com wrote:

>         What is the difference between these two statements?

>         "TButton(Sender)" and "(Sender as TButton)"

My understanding of the difference is that:

  The second uses the AS RTTI (Runtime Type Information) Operator and  
preforms a typesafe typecast of a object to a descentent, raising an  
exception if invalid.  

  The first uses a pointer typecast.

  I think the rule of thumb is to always use the AS operator, unless you
are 100% sure that it is always going to be a valid typecasting.  The
pointer typecasting does not have the overheard that the AS operator has
with its exception handling.

Lloyd

 

Re:"TButton(Sender)" and "(Sender as TButton)"


On Wed, 04 Mar 1998 14:10:01 -0800, Lloyd Budd <lb...@PFC.Forestry.CA>
wrote:

Quote
>dr...@thjzgn.com wrote:
>>         What is the difference between these two statements?
>>         "TButton(Sender)" and "(Sender as TButton)"

>My understanding of the difference is that:

>  The second uses the AS RTTI (Runtime Type Information) Operator and  
>preforms a typesafe typecast of a object to a descentent, raising an  
>exception if invalid.  

>  The first uses a pointer typecast.

>  I think the rule of thumb is to always use the AS operator, unless you
>are 100% sure that it is always going to be a valid typecasting.  The
>pointer typecasting does not have the overheard that the AS operator has
>with its exception handling.

I agree that you should always use the first method when you can.
However there are many instances where you need something as something
else and can't use as.  This mainly occurs when you are converting
to/from something that is not a descendant from TObject.

Ex.

var
  fc: TFormClass;
begin
  fc := TFormClass(Screen.Forms[0].ClassType);
  with fc.create(self) do
    show;
end;

-Shad

Re:"TButton(Sender)" and "(Sender as TButton)"


Quote
>I agree that you should always use the first method when you can.
>However there are many instances where you need something as something
>else and can't use as.  This mainly occurs when you are converting
>to/from something that is not a descendant from TObject.

Another example of when you can't use the 'as' construct is if the object you
are referring to is in an array.  If you use the objects property of a
TStringList, for example, to operate on those objects, the following line fails:

   (myList.Objects[0] as TmyObject).MyMethod() ;

while this line works fine:

   TmyObject(myList.Objects[0]).MyMethod() ;

--
Clayton Neff
Software Project Leader
The Personal Marketing Company, Inc.
11843 West 83rd Terrace
Lenexa, KS  66214
(913)492-0322
clay...@tpmco.com

Other Threads