1

How can I know if an object (TObject) is a generic TList<T>.

The object I get can be a TList<TWhateverObject> or just a TWhateverObject

Can also be a TList<THelloWorld>

In my code I won't use this:

  If (oObject is TList<TWhateverObject>) or
     (oObject is TList<THelloWorld>)

  then begin
    oObject.Free;
  end;

But if possible more like this:

  If (oObject.IsList)
  then begin
    oObject.Free;
  end;

Is there some function in Delphi for that or must I create a helper for TObject (IsList) that search in the RTTI if property add, clear, items, count exist in the object.

Stefan Glienke
  • 20,860
  • 2
  • 48
  • 102
Ravaut123
  • 2,764
  • 31
  • 46
  • 1
    Tuo can try with the `is` keyword like `if (Sender is TObject) then`. Your question is not very specific, do you mean a TList? – Alberto Miola May 04 '17 at 09:35

1 Answers1

3

Unfortunately you cannot use the is operator here since you are checking if the class is any specialization of a generic type (TList<T> in your case).

Since Delphi does not have the concept of open generic types (see this question about them in .Net) it is not quite as simple.

However you can use some tricks and analyze the typeinfo/classname. So in order to check if your instance is a TList<something> you just have to check if the classname matches TList<*> or if it inherits from a class where it does.

In Spring4D we need this quite a few times so I added this functionality to our RTTI helpers.

There it looks like this (add Spring.Reflection.pas to the uses):

TType.GetType(oObject).IsGenericTypeOf('TList<>');
Community
  • 1
  • 1
Stefan Glienke
  • 20,860
  • 2
  • 48
  • 102