Wednesday, March 16, 2005

Typecasting in Delphi

I was just explaining this to someone so I thought I would blog about it for the world. It is a basic concept in Delphi, but an important one to know.

There are two ways to type cast something in Delphi. You can use

(Instance as Type).member

or

TType( Instance ).member

The diferences is using AS checks to make sure Instance is a TType first, and if not raises an exception. Technically if you use an IS first then the AS is redundant. When you don't use is then it will attempt to typecast even if the cast is invalid.

The syntax to use IS:

if ( Instance is TType ) then
begin
  TType( Instance ).member. . . .
end
else
begin
  // alternative condition
end;

When using AS you could use exception handling to have the same results.

No comments: