0

I'm trying to add an Append method to the System.Generics.Collections.TArray type.

unit uMyArray;

interface

uses
  System.Generics.Collections;

type
  TArray = class(System.Generics.Collections.TArray)
  public
    class procedure Append<T>(var AValues: array of T; const AItem: T); static;
  end;

implementation

class procedure TArray.Append<T>(var AValues: array of T; const AItem: T);
begin
  SetLength(AValues, Length(AValues) + 1);
  AValues[Length(AValues) - 1] := AItem;
end;

end.

On compiling I get the following error on the SetLength line:

[dcc32 Error] uMyArray.pas(18): E2008 Incompatible types

3
  • Why don't you use TList? Commented Apr 3, 2020 at 12:02
  • Bit of an antipattern, this increase the length of the array by one. Can result in fragmented address space. Commented Apr 3, 2020 at 12:03
  • You shouldn't append one element at a time. See stackoverflow.com/a/5756206/282848 Commented Apr 3, 2020 at 12:05

1 Answer 1

3

You cannot resize an open array parameter. You need to pass TArray<T>.

Change

class procedure Append<T>(var AValues: array of T; const AItem: T); static;

to

class procedure Append<T>(var AValues: TArray<T>; const AItem: T); static;
Sign up to request clarification or add additional context in comments.

Comments

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.