Initialising dynamic arrays - take 2
In my earlier post on this subject I presented some methods to use to initialise and clone dynamic arrays. Some comments to that post suggested a simpler approach using compiler features I didn't know existed. In this post I've simply collected the information from those comments together in one place.
To initialise an array from literal values you can use the special array constructor provided by the compiler:
uses Types; var A: TIntegerDynArray; begin A := TIntegerDynArray.Create(1,2,3,4); ... end;
This also works when you define your own array types, for example:
var TMyByteArray = array of Byte; begin A := TMyByteArray.Create(1,2,3,4); ... end;
And it also works for the TArray<T> generic array type:
var IntArray: TArray<Integer>; StrArray: TArray<string>; begin IntArray := TArray<Integer>.Create(1, 2, 3); StrArray := TArray<string>.Create('bonnie', 'clyde'); ... end;
The above constructors will only initialise an array from constant values. To make a copy of an existing dynamic array we can use a single parameter version of the Copy procedure as follows:
uses Types; var A1, A2: TIntegerDynArray; begin A1 := TIntegerDynArray.Create(1,2,3,4); A2 := Copy(A1); ... end;
So we don't really need the TArrayEx.CloneArray<T> method I presented in the earlier post because Delphi already has the functionality built in. Duh!
Thanks a lot to Chris who commented on the original post to point these matters out.
Comments
Post a Comment
Comments are very welcome, but please be aware that I moderate all comments, so there will be a delay before your comment appears.
Advertising spam and the rare abusive, hateful or racist comments will be blocked and reported.
Finally, should you have a query about, or a bug report for, one of my programs or libraries please use the relevant issue tracker rather than posting a comment to report it.
Thanks