---- Borland's Delphi Discussion List <[email protected]> wrote:
>
> Related to this TObjectList/TComponentList discussion,
> can somebody explain the difference between:
>
> (TObjectList[i] as TSomething)
> and
> TSomething(TObjectList[i])
>
> Both codes access the same object; one is using the 'as' operator the
> second one is using a direct typecast. But what are the differences?
> Is one of them faster than the other? Should one of them be used in some
> cases more than the other?
The difference is the "as" operator invokes Delphi's class management logic and
actually checks that what you're saying is a TSomething is actually a
TSomething and throws an exception if it's not, a frequently useful safety net.
By directly typecasting using TSomething() you're insisting to the compiler
that you know what you're doing and that what you're casting is DEFINITELY a
TSomething (and if, perchance, it's not a TSomething you may find yourself in
some deep d**d** when you treat it as such, spectacular crashes are to be
expected).
Now, you may then ask why not always use "as"? Because the class hierarchy
checking is expensive in terms of time and processing; wheras direct
typecasting doesn't incurr that penalty. So, "as" should be used only when
necessary.
Just FYI, the "is" operator invokes the same class validation logic as the "as"
operator, so some common code you see like this is redundant:
if (MyObject is TSomething) then
(MyObject as TSomething).Property := SomeValue;
By using "is" like that you've already established that MyObject is a
TSomething, so it's safe to proceed like so:
if (MyObject is TSomething) then
TSomething(MyObject).Property := SomeValue;
HTH
Stephen Posey
[EMAIL PROTECTED]
_______________________________________________
Delphi mailing list -> [email protected]
http://www.elists.org/mailman/listinfo/delphi