Search code examples
arraysdelphigenericsdelphi-xe7generic-collections

Why does generic TArray Create syntax differs from other class functions?


I've noticed something that appears to me as an inconsistency in the generic TArray syntax (and drives me crazy...)

The "constructor" function requires to be called by specifying the type before the function name.

MyArray := TArray<Integer>.Create(3, 2, 1);

The other class functions requires to be called by specifying the type after the function name

TArray.Sort<Integer>(MyArray);

Is there a pratical reason why they did that?


Solution

  • The first TArray is a system type definition of array of T. The creation could be written this way as well:

    MyArray := [3,2,1]; 
    

    The second TArray is a class defined in Generics.Collections.

    They have nothing to do with each other.


    Note also that the TArray class way of using generics is called Parameterized Methods.

    Type
      TArray = class
        ...
        class procedure Sort<T>(var Values: array of T); overload; static;
        ...
      end; 
    

    That is a way to reduce code duplication.