Does anyone know if it is possible to initialize a record constant array?
procedure TForm1.Button1Click( Sender: TObject );
type
TMyRec = record
A: Integer;
end;
const
MyArray: TArray< TMyRec > = [ ?, ?, ? ];
begin
end;
thanks!
Every time you have a question about Delphi, the official documentation should be the first place you visit.
In this case, combining the knowledge from sections Array Constants and Record Constants, we realise that the following syntax is valid:
type
TMyRec = record
A, B: Integer;
end;
const
MyArray: array[0..2] of TMyRec =
(
(A: 1; B: 5),
(A: 2; B: 10),
(A: 3; B: 15)
);
Initially, the question talked about static arrays, but its suggestion TArray<TMyRec>
is in fact a dynamic array. By definition, TArray<T> = array of T
.
Since Delphi XE7, you can create dynamic array typed constants, as long as the elements are of simple enough types:
const
A: TArray<Integer> = [11, 22, 33];
S: TArray<string> = ['alpha', 'beta', 'gamma'];
Since Delphi 10.3, you can even make inline constant declarations, in which case the RHS can even depend on runtime functions. But these are quite far from "true" constants. Think of them as read-only (or assign-once) variables:
begin
const MyArray: TArray<TPoint> = [Point(1, 5), Point(2, 10), Point(3, 15)];
Hence, if you make a function that creates your record (perhaps a record constructor), you can use an inline constant declaration to create such a constant dynamic array of your record:
type
TMyRec = record
A, B: Integer;
end;
function MyRec(A, B: Integer): TMyRec;
begin
Result.A := A;
Result.B := B;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
const MyArray: TArray<TMyRec> = [MyRec(1, 5), MyRec(2, 10), MyRec(3, 15)];
end;
If you are willing to give up some type compatibility, you can also use type inference:
procedure TForm1.FormCreate(Sender: TObject);
begin
const MyArray = [MyRec(1, 5), MyRec(2, 10), MyRec(3, 15)];
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With