Search code examples
arraysclassdelphipropertiesrecords

Implement property read and read&write for fields of an array of records, inside a class


I would like to know if I can create an array of records in a class, where some fields are read-only properties, while others are for read and write.

I could think an example like this:

unit clsCustomers;

interface

uses
  Classes;

type

  TUnitsCategory = (type1, type2, type3, type4);

  TCustomer = record
    ID       : LongWord;
    name     : string[25];
    surname  : string[25];
    category : TUnitsCategory;
  end;
  TCustomers = array of TCustomer;

  CCustomers = class
    private
      mycustomers : TCustomers;
    protected
    ...
    published
      property customer[index: LongWord]: TCustomers           //
        read mycustomer[index].ID;                             // <-- just to say...
        read mycustomer[index].name  write mycustomer[index].name; // 

  end;

Here we have an array of customers, that I want to be accessible through the instance of this class...

I read about how to implement an array property and I wondered if I would like to have the "ID" field as read only, whereas other fields accessible in read and write.


Solution

  • I think the closest you can get is something like this:

    CCustomers = class
    private
      mycustomers : TCustomers;
    public
      property customerID[index: LongWord]: LongWord read mycustomers[index].ID;                            
      property customerName[index: LongWord] read mycustomers[index].name write mycustomers[index].name;
      ...
    end;