Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass generic array as open array parameter in Delphi?

I have an enumerated type and I need to pass an array of this type as parameter:

type
  TTest = (a,b,c);


procedure DoTest(stest: TArray<TTest>);

When I compile

DoTest([a]);

I receiv the error below:

Error: E2010 Incompatible types: 'System.TArray' and 'Set'*

So, how can I call DoTest without creating a variable of type TArray<TTest>?

like image 687
AnselmoMS Avatar asked Sep 04 '26 12:09

AnselmoMS


2 Answers

I don't have a Delphi compiler available right now, so I cannot verify this, but to me

procedure DoTest(stest: TArray<TTest>);

doesn't declare stest as an open array parameter, but a dynamic array parameter. You do want

procedure DoTest(const stest: array of TTest);
like image 153
Andreas Rejbrand Avatar answered Sep 08 '26 16:09

Andreas Rejbrand


One way to do what you want is to change the parameter to an open array of TTest, i.e.

procedure DoTest(const stest: array of TTest);

But supposed you don't want to change the parameter, and really want it to be a TArray<TTest>, then you can simply use the array pseudo-constructor syntax to call it (in almost all versions of Delphi, except the very old ones). Say you have something like:

type
  TTest = (a, b, c);

procedure DoTest(const stest: TArray<TTest>);
// simple demo implementation
var
  I: Integer;
begin
  for I := Low(stest) to High(stest) do
    Write(Integer(stest[I]), ' ');
  Writeln;
end;

Then it can be called, using the Create syntax without having to declare a variable or having to fill it manually. The compiler will do this for you:

begin
  DoTest(TArray<TTest>.Create(a, c, b, a, c));
end.

The output is, as expected:

0 2 1 0 2
like image 24
Rudy Velthuis Avatar answered Sep 08 '26 18:09

Rudy Velthuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!