delphidelphi-xe5

Forward declarations for record types (or arrays)


I want to do this in XE5:

type
  TMyRec = record
    // fields
    class function GetList: TMyRecArr; static;
  end;

  TMyRecArr = array of TMyRec;

I've already seen "Forward declarations for record types" and "how to do a typed forward declaration?", but they seem irrelevant since my problem is not passing the record as a parameter.


Solution

  • You cannot use a forward declaration to declare a record type or an array type. But not to fear. You can use a generic dynamic array, TArray<T>.

    type
      TMyRec = record
        class function GetList: TArray<TMyRec>; static;
      end;
    

    This is actually better than declaring TMyRecArr as per the code in your question. That's because the generic TArray<T> has more flexible type identity than a traditional dynamic array type. You can use TArray<T> with generic types defined in libraries that are independent and unaware of your code.

    Now, you could declare the type like this:

    type
      TMyRec = record
        type TMyRecArray = array of TMyRec;
        class function GetList: TMyRecArray; static;
      end;
    

    And then your array type is TMyRec.TMyRecArray. But I urge you not to do this. You'll have a type that can only be used with you code, and cannot be used with third party code.

    In summary, TArray<T> is your friend.