1

In System.Generics.Collections, the TArray type has class functions only.

For example:

class procedure Sort<T>(var Values: array of T); overload; static;

This implies the only accepted syntax is the following:

var
  Arr : TArray<integer>;
begin
  SetLength(Arr, 2);
  Arr[0] := 5;
  Arr[1] := 3;

  TArray.Sort<integer>(Arr);
end;

I would like to define an object's function in order to sort the values of the generic array using the following syntax:

var
  Arr : TArray<integer>;
begin
  SetLength(Arr, 2);
  Arr[0] := 5;
  Arr[1] := 3;

  Arr.Sort();
end;
Fabrizio
  • 7,603
  • 6
  • 44
  • 104
  • 2
    The type ``TArray`` in Unit ``System`` is not the same as the ``TArray`` class in ``System.Generics.Collections``. What about using a record helper? See your own [Q and the accepted A](https://stackoverflow.com/q/42767205/11329562) for more details – Delphi Coder Mar 11 '20 at 08:47
  • @DelphiCoder: This is a different question, I want to use generic arrays – Fabrizio Mar 11 '20 at 09:01
  • @Fabrizio That's not at all clear in the question though is it? `TArray.Sort()` makes no requirement that you pass a generic array. – David Heffernan Mar 11 '20 at 09:17
  • @DavidHeffernan: Agree, it could have been easily misunderstood... I've updated the question – Fabrizio Mar 11 '20 at 09:27
  • 1
    That's an open request for quite some time: https://quality.embarcadero.com/browse/RSP-10336 – Stefan Glienke Mar 11 '20 at 12:29

1 Answers1

1

You can define helpers for non-generic dynamic arrays, or for fully specialized generic dynamic arrays. For instance, you can write:

type
  TMyArray1 = array of Integer;
  TMyArray2 = TArray<Integer>;

  TMyArrayHelper1 = record helper for TMyArray1
  end;
  TMyArrayHelper2 = record helper for TMyArray2
  end;
  TMyArrayHelper3 = record helper for TArray<Integer>
  end;

This allows you to add methods to the scope of such arrays.

So you can write

type
  TIntegerArrayHelper = record helper for TArray<Integer>
    procedure Sort;
  end;

procedure TIntegerArrayHelper.Sort;
begin
  TArray.Sort<Integer>(Self);
end;

However, what you cannot do is write:

  TMyArrayHelper<T> = record helper for TArray<T>
  end;

The compiler simply does not support generic helpers.

None of this is worthwhile in my view, just call:

TArray.Sort<T>()

directly. Adding a record helper, and having to make one for each element type that you wish to support, seems to me like a cost that does not justify the return.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490