How to do for in TObjectList?

Ian Boyd picture Ian Boyd · Sep 29, 2014 · Viewed 15.1k times · Source

I am trying to use for in to iterate a TObjectList:

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, Contnrs;

var
    list: TObjectlist;
    o: TObject;
begin
    list := TObjectList.Create;
    for o in list do
    begin
        //nothing
    end;
end.

And it fails to compile:

[dcc32 Error] Project1.dpr(15): E2010 Incompatible types: 'TObject' and 'Pointer'

It seems as though Delphi's for in construct does not handle the untyped, undescended, TObjectList an as enumerable target.

How do i enumerate the objects in a TObjectList?

What i do now

My current code is:

procedure TfrmCustomerLocator.OnBatchDataAvailable(BatchList: TObjectList);
var
   i: Integer;
   o: TObject;
begin
   for i := 0 to BatchList.Count-1 do
   begin
      o := BatchList.Items[i];

      //...snip...where we do something with (o as TCustomer)
   end;
end;    

For no good reason, i was hoping to change it to:

procedure TfrmCustomerLocator.OnBatchDataAvailable(BatchList: TObjectList);
var
   o: TObject;
begin
   for o in BatchList do
   begin
      //...snip...where we do something with (o as TCustomer)
   end;
end;    

Why use an enumerator? Just cause.

Answer

Teun Pronk picture Teun Pronk · Sep 29, 2014

Using generics you can have a typed objectlist (just noticed the comment but ill finish this anyhow)

And if you're looking for a good reason to use a TObjectList<T> that reason will be that it saves you a lot of type casting in your code

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, Generics.Collections;
Type
  TCustomer = class
  private
  public
    //Properties and stuff
  end;

var
    list: TObjectlist<TCustomer>;
    c: TCustomer;
begin
    list := TObjectList<TCustomer>.Create;
    for c in list do
    begin
        //nothing
    end;
end.