CubicDesign 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 first is a checked type cast. If the left operand is not an instance 
of the right operand class, then a run-time error occurs, usually in the 
form of an exception.

The second is an unchecked type cast. If the object is not an instance 
of the class, nobody will tell you, so you'd better be absolutely sure 
you've matched the class with the instance.

A checked type cast takes longer. It involves a function call and as 
many iterations of a loop as are necessary to determine the object's 
ancestry. An unchecked type cast takes zero time; the compiler simply 
assumes that the value of some type is really a value of the given type, 
and lets you use it that way.

A checked type cast will tell you when you've done something wrong. An 
unchecked type cast won't.

It's a trade-off between time and safety. If you're already sure that 
the object is of the class you're type-casting to, then there's no need 
to check. In particular, the following code is redundant:

if x is T then
   x as T ...

If you've already checked an object's type with "is," then you don't 
need to use "as" for a checked type cast. Just use the unchecked type 
cast instead.

-- 
Rob
_______________________________________________
Delphi mailing list -> [email protected]
http://www.elists.org/mailman/listinfo/delphi

Reply via email to