The use of Generics to initialize an array is very handy, but I couldn't find an Add method, so I infere from this (correct me if I'm wrong) that in that case, I must use the traditional way: SetLength to enlarge the array and then assign the new value to the recently added item of the array. Is that so?
-
Generics don't "initialize an array" by any means, so I'm not sure what that's supposed to mean. *Dynamic* arrays have a pseudo constructor that allows you to initialize them, but there's no real method to do so. – Ken White Aug 14 '14 at 17:28
-
Presumably you mean `TArray
` right? – David Heffernan Aug 14 '14 at 18:58 -
You could have a look at [`TList
`](http://docwiki.embarcadero.com/Libraries/en/System.Generics.Collections.TList), which has an `Add()` method and also an `AddRange()` method. – LU RD Aug 14 '14 at 19:49
2 Answers
Generics do not initialize arrays, or anything else for that matter. They are simply a means of declaring flexible types, not data. Do not be confused by dynamic array constructors, which allow you to use constructor-like synax to initialize a dynamic array with values, but that has nothing to do with Generics.
Arrays, whether Generic or otherwise, do not have any methods at all, let alone an Add()
method. You have to code the logic manually, as you described - increase the array length and then assign a value to the newly allocated slot. That is the only option currently available.

- 555,201
- 31
- 458
- 770
-
As @DavidHeffernan said, he probably uses `TArray
`, and that pretty much *looks* like a generic class, even if it isn't. And as @LURD says, he could use `TList – Rudy Velthuis Aug 15 '14 at 07:15` instead.
I am assuming that since you are looking for an Add()
method, that you really don't want an Array at all.
Instead you probably want a true generic (Array-like) Collection like TArrayList<T>
. It has everything an Array
does, plus all the collection methods like Add()
, Remove()
, AddRange()
, etc
The generic TList<T>
would also work, but, lacks all the familiar Array methods and properties that you might be wanting.
You might also want to check out some of other generic Collections classes like TDictionary<T>
, THashTable<T>
, etc...
-
2
-
sorry... I was confused with .Net a bit.. lol. TList
is what you want. `ArrayList – Aug 22 '14 at 14:51 -
1Here's an interesting SO Q&A that may not apply directly, but has some cool stuff about playing with and extending Generics: http://stackoverflow.com/questions/1600239/class-helper-for-generic-class – Aug 22 '14 at 14:55