How can I declare an array property?

24,012

Solution 1

Your line

property Fields : array read FFields;

is invalid syntax. It should be

property Fields[Index: Integer]: TFieldSpec read GetField;

where GetField is a (private) function that takes an integer (the Index) and returns the corresponding TFieldSpec, e.g.,

function TTableSpec.GetField(Index: Integer): TFieldSpec;
begin
  result := FFields[Index];
end;

See the documentation on array properties.

Solution 2

I agree the answer regarding INDEXED properties, given by Andreas, is the solution the poster is looking for.

For completeness, for future visitors, I'd like to point out that a property can have an array type, as long as the type is named. The same applies to records, pointers, and other derived types.

type
  tMyColorIndex = ( Red, Blue, Green );
  tMyColor = array [ tMyColorIndex ] of byte;

  tMyThing = class
    private
      fColor : tMyColor;
    public
      property Color : tMyColor read fColor;
  end;
Share:
24,012
user1730626
Author by

user1730626

Updated on July 09, 2022

Comments

  • user1730626
    user1730626 almost 2 years

    I constructed class system

      TTableSpec=class(Tobject)
      private
        FName : string;
        FDescription : string;
        FCan_add : Boolean;
        FCan_edit : Boolean;
        FCan_delete : Boolean;
        FFields : array[1..100] of TFieldSpec;
      public
        property Name: String read FName;
        property Description: String read FDescription;
        property Can_add : Boolean read FCan_add;
        property Can_edit : Boolean read FCan_edit;
        property Can_delete : Boolean read FCan_delete;
        property Fields : array read FFields;
      end;
    

    Thus in TableSpec Fields property shall be the list of fields (I used TFieldSpec array). How to organize the list of fields (using or without using an array) as as a result of compilation I receive an error

    [Error] Objects.pas(97): Identifier expected but 'ARRAY' found
    [Error] Objects.pas(97): READ or WRITE clause expected, but identifier 'FFields' found
    [Error] Objects.pas(98): Type expected but 'END' found
    [Hint] Objects.pas(90): Private symbol 'FFields' declared but never used
    [Fatal Error] FirstTask.dpr(5): Could not compile used unit 'Objects.pas'
    
    • Wouter van Nifterick
      Wouter van Nifterick over 11 years
      Unless you're certain that you'll need exactly 100 fields, I'd create a type like type TFields=Array of TFieldSpec and then specify the fields attribute as FFields:TFields.
    • Wouter van Nifterick
      Wouter van Nifterick over 11 years
      Renamed the title, and removed irrelevant code. We don't need to see the entire unit in order to pinpoint the problem here.
    • CodesInChaos
      CodesInChaos over 11 years
      Are you sure you want a property with an array type, or rather an indexer?
  • john_who_is_doe
    john_who_is_doe almost 6 years
    Yes, sorry thats escaped my attention. (: