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 don't comment here if:
1) You have a query about, or a bug report for, one of my programs or libraries. Most of my posts contain a link to the relevant repository where there will be an issue tracker you can use.
2) You have a query about any 3rd party programs I feature, please address them to the developer(s) - there will be a link in the post.
3) You're one of the tiny, tiny minority who are aggressive or abusive - in the bin you go and reported you will be!
Thanks