Phillip Roux
Phillip Roux

Reputation: 1029

Store Generic Array in Class using Delphi XE

Using the structure below, how can I define my TAnimalCollection class in order to store my collection? Calling either SelectAll or SelectTop10 will update the SelectedRecords. Removing the private field allows the code to compile, but there is no mechanism to then store the returned result set.

  TDog = class
  private
    FBreed: string;
  public
    property Breed: string read FBreed write FBreed;
  end;

  TCat = class
  private
    IsWild: string;
  public
    property IsWild: string read FIsWild write FIsWild;
  end;

  TMyArray<T> = array of T;

  TAnimalCollection = class
  private
    SelectedRecords: TMyArray<T>; // Generates: Undeclared Identifier: 'T'
  public
    function SelectAll<T>: TMyArray<T>;
    function SelectTop10<T>: TMyArray<T>; 
    // Other Methods
  end;

Upvotes: 3

Views: 1158

Answers (1)

Rob Kennedy
Rob Kennedy

Reputation: 163277

First, you don't need TMyArray; the built-in TArray type does the same thing.

The compiler is correct, though. In your field declaration, there's no such thing as T. The generic argument needs to be introduced on the left of a declaration before it can be used on the right. If Delphi supported generic fields, the declaration would look like this:

SelectedRecords<T>: TArray<T>;

But it doesn't, and you wouldn't want it to in this case anyway. You apparently want to store two completely unrelated classes together in the same array simultaneously. An array is always of a single type. The only single type that unifies TDog and TCat is TObject, so your array needs to be of that type:

SelectedRecords: TArray<TObject>;
// or, more conventionally,
SelectedRecords: array of TObject;

You're welcome to declare a "generic array," but only as a field of a generic class or a variable of a generic method. If you could declare a standalone generic array, try to think of when the actual type of the array elements would be determined. If not at the point you declare the array, then when? With classes and methods, you specify the type argument(s) when you declare a variable of the class, instantiate the class, or call the method. Those are uses that are separate from their declarations, and each use is distinct. When you declare a variable, you must use it the same way you declared it — a variable's type cannot change without recompiling the program.

Upvotes: 6

Related Questions