Search code examples
delphimetaclassclass-reference

Test if class from a class reference (metaclass) variable is TMyClass


I want to know whether the object that would be created from a class reference is an instance of a particular class or any of its descendants.

In other words, I want a Boolean expression such as

var is TMyClass

but where var is replaced with an expression involving a class reference variable. It sounds easy but has me completely stumped.

I could create an instance var := classRefVar.Create, test it, and then destroy it, but that's a huge overhead.

Oddly, the compiler won't let me have

classRefVar(nil) is TMyClass

but is happy with the seemingly equivalent syntactically, but useless

TMyClass(nil) is TMyClass

Obviously, the expression

classRefVar = TMyClass

is no good because the classRefVar might refer to a descendent of TMyClass.

I'm expecting to kick myself when I see the answer...


Solution

  • Easy:

    ClassRefVar.InheritsFrom(TMyClass)