user3764855
user3764855

Reputation: 297

Invalid Typecast

When I try to cast Array of Integer to TArray<Integer> in a procedure I get an error E2089 Invalid typecast. How can I type cast it so that it will work?

program Project11;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Math;

type
  TArrayManager<T> = record
    class procedure Shuffle(var A: TArray<T>); static;
  end;

class procedure TArrayManager<T>.Shuffle(var A: TArray<T>);
var
  I, J: Integer;
  Temp: T;
begin
  for I := High(A) downto 1 do
  begin
    J := RandomRange(0, I);
    Temp := A[I];
    A[I] := A[J];
    A[J] := Temp;
  end;
end;

procedure Test(var A: Array of Integer);
begin
  TArrayManager<Integer>.Shuffle(TArray<Integer>(A)); // Invalid typecast????
end;

var
  A: Array of Integer;
begin
  // TArrayManager<Integer>.Shuffle(TArray<Integer>(A)); // Works
  Test(A);

end.

Upvotes: 3

Views: 3398

Answers (2)

David Heffernan
David Heffernan

Reputation: 613592

You cannot cast an open array parameter to a dynamic array. They are simply incompatible. If you wish to operate on a slice of the array, without copying, I'm afraid that you will need to pass the array and the indices separately. Like this:

procedure Foo(var A: TArray<Integer>; Index, Count: Integer);
begin
  // operate on A[Index] to A[Index+Count-1]
end;

Upvotes: 3

Mason Wheeler
Mason Wheeler

Reputation: 84650

The type "array of X" means something different as a parameter than as a variable. Here it's an open array, which is actually something very different from a dynamic array.

If you want to pass around a dynamic array, you should make the param type TArray<integer>.

Upvotes: 3

Related Questions