Search code examples
delphiclass-design

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


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.


Solution

  • I think ive solved what i was trying to do, It hit me on the head last night.

    iParentInterface = interface(IUnknown);
    TChild1 = class(TInterfacedObject,iParentInterface);     
    TChild2 = class(TInterfacedObject,iParentInterface);   
    
    Procedure DoSomething(obj:iParentInterface);