6

I'm using this code to get the element type of an array

{$APPTYPE CONSOLE}    
uses
  Rtti,
  SysUtils;

type
  TFooArray= array  of TDateTime;

Var
  T : TRttiType;
begin
  try
     T:=TRttiContext.Create.GetType(TypeInfo(TFooArray));
      Writeln(TRttiArrayType(T).ElementType.Name);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

but the application fails with an access violation on this line

Writeln(TRttiArrayType(T).ElementType.Name);

How I can get the element type of an array using the RTTI?

Salvador
  • 16,132
  • 33
  • 143
  • 245

1 Answers1

14

You cast is wrong the TRttiArrayType is for static arrays (and your array is dynamic), to fix the issue use the TRttiDynamicArrayType instead like so :

 Writeln(TRttiDynamicArrayType(T).ElementType.Name);
RRUZ
  • 134,889
  • 20
  • 356
  • 483
  • 2
    And it's also worth saying that forcing the type cast `TRttiArrayType(T)` or `TRttiDynamicArrayType(T)` is not a good habit. You should do it only if you are *sure* that the types match - which is not the case in your code. IMHO writing `(T as TRttiArrayType)` could make sense, or first test `if T is TRttiArrayType then...` which performs the same (but do not trigger any exception), but can be made once before a loop, for instance. It will avoid any similar type confusion. – Arnaud Bouchez Dec 31 '11 at 10:11
  • Agree with Arnaud Bouchez, TSomeClass(VarSomeObj) is only applicable in `if VarSomeObj is TSomeClass then with TSomeClass(VarSomeObj) do Something` – OnTheFly Dec 31 '11 at 12:38