Search code examples
delphiparameterscompiler-errorstobjectlist

Delphi Sent TObjectList like var parameter


I have class

TFolder = class
    NODE_INDEX: Integer;
    FIRST_INDEX : Integer;
    CODE_NAME: AnsiString;
    NAME: AnsiString;

    constructor Create(NewNODE_INDEX, NewFIRST_INDEX: Integer; NewCODE_NAME, NewNAME: AnsiString);
    destructor Destroy; override;

  end;

And i have Type

type
  TFolderList = class (TObjectList<TFolder>)
  end;

Then i try to use this type

TAccount = class
  ...
  FOLDERS: TFolderList;
public
  constructor Create(...);
  destructor Destroy; override;

  procedure LoadFoldersFromDisk(var _objectList: TFolderList);
end;

When i try to send my TObject list like parameter

procedure TForm1.FormCreate(Sender: TObject);
begin 
  olLOCALFolders := TObjectList<TFolder>.Create();
  Account.LoadFoldersFromDisk(olLOCALFolders);
end;

I get error "Types of actual and formal var parameters must be identical". What I'm doing wrong?


Solution

  • Just replace the TObjectList<TFolder> wtih the TFolderList you defined eariler:

    procedure TForm1.FormCreate(Sender: TObject);
    begin 
      olLOCALFolders := TFolderList.Create();
      Account.LoadFoldersFromDisk(olLOCALFolders);
    end;
    

    However, you probably do not need to use var parameter here - the method name LoadFoldersFromDisk suggest that the method will populate the list sent as parameter with items, and for that you can send the list by value. You only need to use var parameter if the method would alert the list object's memory location (as opposed to it's content), ie when the LoadFoldersFromDisk could free the original list and create new one.