Why can't I return arbitrary array of string?

arrays, delphi, delphi-xe3

Solution

No, it's not the same thing. In

procedure MyProc(const ADynData: array of string);

the argument is an open array parameter, which is not the same thing as an 'ordinary' dynamic array. The `[..]` syntax can only be used to create open arrays in open array parameters of functions. (Otherwise, `[..]` is used to specify sets in code, such as `Font.Style := [fsBold, fsItalic]`. But sets can only have ordinal types as their 'base types', so there is still no such thing as 'set of string'.)

In other words, it is not possible to write a dynamic array in code like you try in your second code snippet,

function MyFunc: TStringDynArray;
begin
  result := ['Data1', 'Data2']; // Won't work.
end;

However, in new versions of Delphi, it is almost possible:

type
  TStringDynArray = array of string;

function MyFunc: TStringDynArray;
begin
  result := TStringDynArray.Create('A', 'B');
end;

Finally,

function MyFunc: TStringDynArray;
const
  CDynData: array[0..1] of string = ('Data1', 'Data2');
begin
  result := CDynData;
end;

won't work because `TStringDynArray` is a dynamic array, while `CDynData` is a static array, which are two different fundamental types.

Problem

The compiler allows me to do the following: ``` procedure MyProc(const ADynData: array of string); ``` or ``` procedure MyProc(const ADynData: TStringDynArray); ``` and pass arbitrary data like so: ``` MyProc(['Data1', 'Data2']); ``` However, won't allow ``` function MyFunc: TStringDynArray; .... function MyFunc: TStringDynArray; begin Result := ['Data1', 'Data2']; end; ``` or ``` function MyFunc: TStringDynArray; const CDynData: array[0..1] of string = ('Data1', 'Data2'); begin Result := CDynData; end; ``` Why is this? Isn't this technically the same thing? For these particular scenarios what is the recommended (and most efficient) way of returning an arbitrary array of string?

Original source

Related problems