Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Type casts

Status
Not open for further replies.

donvittorio

Programmer
Jul 17, 2003
122
GB
Hello all,

Can anybody explain to me the difference between the two methods of type casting? For example:

(Sender as TButton).Caption := 'Button1'
or
TButton(Sender).Caption := 'Button1'

I know that there must be a difference because sometimes Delphi does not like the second way of type casting, but I've never figured out why.

Steve
 
Hi.
This is from the Delphi help file:

It is sometimes useful to treat an expression as if it belonged to different type. A typecast allows you to do this by, in effect, temporarily changing an expression's type. For example, Integer('A') casts the character A as an integer.

The syntax for a typecast is

typeIdentifier(expression)

-----------

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.

----------- Explanation.

When (Sender AS TButton), the Sender has to be a TButton,
and are therefore no typecast.

The real typecase is TButton(Sender) and in this case Sender can be of another type than TButton...

...Anm I right, comments please...


//Nordlund
 
Oopps.. Some vital spelling mistakes, but you may figure it out anyway... :)

//Nordlund
 
Norlund
Of course the typecast will only work if the sender object has the required properies (i.e it is a parent object of the TButton(with a Caption property) or a Tbutton or a decendent of Tbutton.
The difference is that you will only find this out at Runtime when an exception may occur, using the AS construct is safer. But even this should be tested with an
if (sender is TButton) then etc.



Steve
Two things are infinite
The Universe and Human stupidity: Einstein.
(He wasn't too sure about the Universe)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top