Raffaele Rossi
Raffaele Rossi

Reputation: 3137

Delphi generic classes and dynamic arrays

I have read multiple times the answers in this question about the TArray<T> and the array of T. From what I have understood the use of the first is more versatile than the latter because for a dynamic array I should declare a type like...

type
   TMyFlexibleArray = array of Integer;

... that is needed (in certain cases) because I cannot return an array of Integer for example. Instead, of course, I can return a generic type. Dynamic arrays don't have a fixed length and memory for them is reallocated with the SetLength procedure. TArray is a generic class with static methods; the documentation about it states:

You should not create instances of this class, because its only purpose is to provide sort and search static methods.


They have two different natures/functions but do they have the same result (for example when passed as parameter or when I just need a flexible container)? I see that TArray has also some useful method.

Is is correct if I say that TArray<T> is a dynamic array built with generics and type K = array of T is an own dynamic array (a custom one)? In my question I assume that they are equivalent in their function of being dynamic arrays (and I prefer the generic way just for comfort).

Upvotes: 3

Views: 958

Answers (1)

David Heffernan
David Heffernan

Reputation: 613461

Generic dynamic arrays and non generic dynamic arrays are identical in every way, apart from their generic, or otherwise, nature. That is the single difference.

That difference drives decision making in the few scenarios where one can be used but not the other. For instance:

  • For reasons outlined in your question, generic arrays are sometimes necessary when working with generic types.
  • On the other hand, when writing code that you wish to compile on old compilers that pre-date generics, then you cannot use generic arrays.

If this seems obvious, that's because it is. There really is just this one single difference between generic and non-generic arrays.


You also mention the class TArray from System.Generics.Collections. That's a static class containing methods to search and sort arrays. It's completely different from any dynamic array types and something of a distraction here. Although the names are similar, TArray<T> and TArray these are quite different things. Ignore TArray for the purpose of this question.

Upvotes: 9

Related Questions