David
David

Reputation: 477

Find out if Delphi ClassType inherits from other ClassType?

In Delphi, given the following:

TFruit = class;
TFruitClass = class of TFruit;

TApple = class(TFruit);

TRedApple = class(TApple);

If I have a TFruitClass variable, how can I find out if it inherits from TApple? E.g. say I have

var
  FruitClass: TFruitClass;
...
FruitClass := TRedApple;

How can I verify that FruitClass does indeed inherit from TApple in this case? Using FruitClass is TApple only works for class instances.

Upvotes: 5

Views: 3489

Answers (2)

PatrickvL
PatrickvL

Reputation: 4164

I assume you pass the FruitClass variable along to some method, in which case your should read :

  if FruitClass.InheritsFrom(TApple) then

Note that you don't even need to test for nil, as InheritsFrom is a class function, and thus does not need the Self variable to be assigned.

Upvotes: 0

Marjan Venema
Marjan Venema

Reputation: 19346

Use InheritsFrom:

if TApple.InheritsFrom(TFruit) then
  ...

You can also use

var
  Fr: TFruitClass;
  X: TObject;
begin
  if X.InheritsFrom(TFruit) then
    Fr := TFruitClass(X.ClassType);
end;

Upvotes: 14

Related Questions