2

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'

2
  • 1
    This issue is covered in the documentation in the "Array Types and Assignments" section: "Arrays are assignment-compatible only if they are of the same type." TMyStringArray and TArray<string> are NOT the same type. Commented Feb 21, 2020 at 9:30
  • 1
    Just for the sake of completeness, it should be pointed out already here that TArray<string> is a dynamic array of strings; it's defined as array of string. Commented Feb 21, 2020 at 10:15

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

12 Comments

Yes, this is correct. TArray<string> is defined as array of string, so it is a dynamic array of strings, just like array of string (obviously). So it is undesirable and strange that the compiler refuses to consider these types compatible without the cast.
@AndreasRejbrand: I'm using Delphi XE7, does the newer versions accept the assignment without the type cast?
I actually thought that was fixed in 10.3, but now I tried it, and it seems not. I still need to cast. (I know something changed very recently related to this, but I don't quite recall what it was.) But this is how the type system works. Try, for instance, to define type TDynStringArray = array of string; TDynStringArray2 = array of string;. They will not be assignment compatible without a cast...
The best solution these days, I think, it to always use TArray<string> as the dynamic string array type. (It is better than array of string, for instance, because it can be used as a function return type. And it is better than any user-defined type defined as array of string because it is part of the core RTL, so all units agree on it.)
@Fabrizio "does the newer versions accept the assignment without the type cast?" - in your example, no.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.