Fabrizio
Fabrizio

Reputation: 8043

Assign a dynamic array type to a TArray<T> variable

I'm trying to assign a dynamic array type to a TArray<string> variable

type
  TMyStringArray = array of string;

function Test() : TMyStringArray;
begin
  ...
end;

...

var
  MyArray : TArray<string>;
begin
  MyArray := Test();
end;

On compiling, Delphi says:

[dcc32 Error] Unit1.pas(39): E2010 Incompatible types: 'System.TArray' and 'TMyStringArray'

Upvotes: 2

Views: 3217

Answers (1)

Fabrizio
Fabrizio

Reputation: 8043

I did it simply by using a type cast and it seems to work.

I would be glad to know I can fall into some problems doing this way

type
  TMyStringArray = array of string;

function Test() : TMyStringArray;
begin
  SetLength(Result, 2);
  Result[0] := 'Hello';
  Result[1] := 'World';
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  MyArray : TArray<string>;
  i : integer;
begin
  MyArray := TArray<string>(Test());

  i := 0;
  while(i < Length(MyArray)) do
  begin
    ShowMessage(MyArray[i]);
    Inc(i);
  end;
end;

Upvotes: 2

Related Questions