Tag Archives: fpc

Add an array property enumerator in FPC/Lazarus

I’ve been wishing object pascal supported array property enumeration for a long time:

  TTest = class
    // ...
    property Objects[Index: Integer]: TObject read GetObject;
  end;
var
  Test: TTest;
  Obj: TObject;
begin
  //...
  for Obj in Test.Objects do
    //...
end;

Unfortunately, this should not be possible because enumerators can be defined only with the GetEnumerator function in class/record/interface and other types through helper classes.

This is the case in Delphi.

I discovered a bug in FPC that allows to declare an enumerator for an array property. Studying the FPC code, I found out that it does not check if the array property parameters match the property definition. Instead it checks whether an (overloaded) getter function with the supplied parameter set exists. So you create a second parameterless getter function that returns the enumerator and, voila, your “for Obj in Test.Objects do” loop compiles!

  TTest = class
    // ...
    // usual getter
    function GetObject(Index: Integer): TObject; overload;
    // overloaded getter used for the enumerator
    function GetObject: TTestObjectEnumerator; overload;
    property Objects[Index: Integer]: TObject read GetObject;
  end;

TTestObjectEnumerator can be either a class or record – FPC frees enumerators automatically. But there is one thing you have to do in contrast to usual enumerators – you obviously have to define TTestObjectEnumerator.GetEnumerator that returns Self so that the compiler finds the GetEnumerator function (thanks Sven Barth for the idea).

What are the benefits of having such an array property enumerator? Clear and understandable code and also the ability to have enumerator for every array property within an object. As an example consider this code:

procedure TForm1.Check;
var
  Comp: TComponent;
begin
  for Comp in Self do
    // ...
end;

From my POV it’s quite unclear what collection is used for the enumerator. The default enumerator can even be overloaded with a helper, which can lead to unpredictable results.

With the array property enumerator, the code is much clearer and you can use more enumerators in the same object:

procedure TForm1.Check;
var
  Comp: TComponent;
  Cont: TControl;
begin
  for Comp in Components do
    // ...
  for Cont in Controls do
    // ...
end;

Download the example code PropArrayEnum.zip:
arraypropenum.lpr: enable property array enumerator in your own class.
tobjectsenum.lpr: enhance TStrings.Objects with an enumerator (with a helper class).

Further reading:
feature request report
fpc-devel thread 1
fpc-devel thread 2 (a), fpc-devel thread 2 (b)