In Delphi the AS keyword is used for casting an object (or interface) of one type to another.
For example if a class TDeveloper extends (derives from) TPerson as in:
type TDeveloper = class(TPerson)
you can safely cast an instance of type TDeveloper ("aDeveloper") to a TPerson using the (aDeveloper as TPerson) - this is called "as-cast".
What's more you can also use the hard-cast: TPerson(aDeveloper).
The question is: what's the difference between a hard-cast and an as-cast?
Hard-Cast vs. AS-Cast in Delphi
When several controls share an event handling procedure, for example a button and a menu item, you end up using the Sender parameter to identify the control that actually caused the event to be raised.beginUsing the is keyword you can verify the actual runtime class of an object. The "Sender is TButton" checks whether the Sender parameter is a button or any type descending from TButton.
if Sender is TButton then
begin
//do something if the button was clicked
end;
if Sender is TMenuItem then
begin
//do something if the menu item was clicked
end;
end;
After you do the is-check you can cast an object to a type you need to operate with.
With a hard-cast, you are telling the compiler that you know what you expect the object to be. Hard-casts are therefore unsafe - Delphi will not complian if you hard-cast an instance of a TEdit to a TButton as in:
TButton(Edit1).Caption := 'junk code';Will this work? Yes it will! Casting an edit box to a button, then chaning the Caption property of a "button" will result in changing the Text property of the Edit1 edit box.
On the other hand, the safe as-cast will raise the EInvalidCast exception when you try to use the cast value.
//raises "Invalid Type Cast"Contrary to the hard-cast, when the as-cast is used with an object, additional code is generated to verify at run time that the new type is a base class of the referenced object.
(Edit1 as TButton).Caption := 'junk code';
Safe Hard-Cast with the Is-Checking
You'll often find Delphi code like :if Sender is TButton thenWe are combining the safe is-case with the unsafe hard-cast to produce a safe hard-cast.
begin
TButton(Sender).DoSomething;
end
You should generaly use the above code and not the is-check followed by the as-cast since as-casting is "time" consuming - compiler needs to traverse the RTL inheritance chain to see if an object can be casted to the class specified.
The Tricky Hard-Cast
A common scenario of storing integer values along strings inside a string list is a commonly used hard-casting trick in Delphi:var
sl : TStringList;
begin
sl := TStringList.Create;
try
//add integer values as objects
sl.AddObject('One',TObject(1)) ;
sl.AddObject('Two',TObject(2)) ;
//hard cast an object to integer
int := Integer(sl.Objects[0]) ;
finally
sl.Free;
end;
end;
Delphi tips navigator:
» An Invalid Hard-Cast is NIL in Delphi for .NET. Find out why TButton(Edit1) is NIL in Delphi for .NET
« Delete Multiple Selected Items in a TListBox Delphi Control

