How can I determine whether a Delphi object is of a specific class and not any descendant class?

Christopher Chase picture Christopher Chase · Mar 10, 2011 · Viewed 25.9k times · Source

I have these classes and a procedure:

 TParent = class(TObject);
 TChild1 = class(TParent);     
 TChild2 = class(TParent);

 Procedure DoSomething(obj:TParent);

What I would like to do is when obj is a TParent and not a descendant raise an exception.

I thought about doing something like this:

if obj.classname = TParent.classname then raise exception.create....

but it seems a bit hackish (TM)

More: What i intended is to able to pass objects that shared properties/procedures in common. After more thought, the TParent Object isn't really needed at all, what i needed was an interface object shown in my answer.

Answer

David picture David · Mar 10, 2011

You'll probably find the following TObject class methods useful:

  • ClassType - returns the class of an object
  • ClassParent - gives the parent class of the class
  • InheritsFrom - returns if a class inherits from another class (ie, checks the entire inheritance chain). It includes the current class.

So, you could achieve what you want (descends from TParent but not TDescendant?) with something like the following code (untested, don't have Delphi at this moment):

if obj.ClassType.InheritsFrom(TParent)
  and not obj.ClassType.InheritsFrom(TDescendant) then...

Or, if I've misunderstood and you just want to see if an object is a TParent, and not any kind of descendant at all, try:

if obj.ClassType = TParent then...

Delphi was way ahead of its time by providing access to classes via metaclasses, so rather than just checking the class name you can access an actual class object.