Bruice
Bruice

Reputation: 663

Delphi casting with as and Supports difference

What is the difference in casting using Supports vs as keyword, besides that with as I first need to check if cast is possible with is keyword.

Upvotes: 3

Views: 723

Answers (1)

Rob Lambden
Rob Lambden

Reputation: 2293

Supports will provide an interface if that interface is supported.

is determines if a class/interface derives from another class/interface.

as does the same thing as is, but also returns a type-checked cast.

If you have already confirmed with is that a cast will succeed, you don't need to use as, you can just do a direct cast, which is more efficient:

if(pSomeObjectRef is TMyObject) then
  TMyObject(pSomeObjectRef).MyUsefulMethod(...);

As Delphi does not support multiple inheritance, using interfaces is the only way to implement that kind of behavior. An object which can be more than one thing, not just itself or its ancestors.

If you're not using interfaces, you shouldn't need to use Supports().

Using as to cast allows you to cast an object reference to an interface, as well as to a reference to a different class of object. Personally, I don't use as, and I rarely see it in the code I'm looking at. Since as can raise an exception, you ought to take steps to avoid the exceptions, and catch them if they are raised. As you can check these anyway, there should never be a need to use as.

When casting to an interface, rather than relying on the exception to catch the interface not being there, you can use the result of Supports():

if (SysUtils.Supports(pSomeObjectRef, IMyWantedInterface, diInterfaceRef)) then
begin
  diInterfaceRef._AddRef();   // removed when diInterface falls out of scope
  ...
end
else
begin  // it doesn't support the interface!
  ...
end;

Whether you want to catch exceptions (which some people like, some people don't - it does make the code less linear), or code for if..else, is usually a matter of preference. I prefer not to rely on exceptions (but I still have try..finally or try..except blocks), but of course other opinions are available!

Upvotes: 5

Related Questions