opc0de
opc0de

Reputation: 11768

How to implement indexed [] default property

I have a class which holds multiple filenames inside a TStringList. I can access a particular filename by index using:

myclass.stringlistclass[index]

But how can I get an filename using the following syntax?

myclass[index]

Is there a property I can implement to achieve this functionality?

Upvotes: 16

Views: 13398

Answers (2)

Use "default" keyword on the indexed property. There can be one default property per class.

You can have multiple default properties per class, however these default properties must have the same name.

An example:

    property Item[const Coordinate: TPoint]: TSlice read GetSlice write SetSlice; default;
    property Item[x,y: integer]: TSlice read GetSlice write SetSlice; default; 

You can even have the getters and setters share the same name, as long as they have the overload directive.

Upvotes: 14

Marck
Marck

Reputation: 676

private
  function GetColumnValue(const ColumnName: string): string; overload;
  function GetColumnValue(Index: Integer): string; overload;
  procedure SetColumnValue(Index: integer; const Value: string);
public
  property Values[const ColumnName: string]: string read GetColumnValue; default;
  property Values[ColumnIndex: integer]: string read GetColumnValue write SetColumnValue; default;
end;

This means:

  • you can have multiple default indexor properties
  • the multiple indexor properties can have the same name e.g., Values
  • the properties getters can be overloads (i.e. have the same name) e.g., GetColumnValue
  • Delphi will resolve the overloads by type signature

Upvotes: 32

Related Questions