user2383818
user2383818

Reputation: 689

Delphi - Generics - Is there an Add method?

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?

Upvotes: 1

Views: 469

Answers (2)

user3949365
user3949365

Reputation:

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...

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 596256

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.

Upvotes: 4

Related Questions