Lazarus: Generic object List with ObjectPascal

Veröffentlicht von

How to use generic lists in ObjectPascal, an example.

This blog posts will demonstrate a small example on how to use a generic list in Object Pascal.

Ok let’s get started, first our data object. Our list should contain items of the type TFileInfo:

type

  { TFileInfo }

  TFileInfo = class
    private
      fFileName: string;
      fCreatedDate: TDateTime;
      fChangedDate: TDateTime;
    public
      property FileName: string read fFileName write fFileName;
      property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
      property ChangedDate: TDateTime read fChangedDate write fChangedDate;
  end;

We use the TFPGObjectList, which we specialize as TFileInfoList. Here, we also define the generic type TFileInfo

type
  TFileInfoList = class(specialize TFPGObjectList); 

We need to include “fgl”:

uses fgl;

No we can declare our list of the new type:

FileList: TFileInfoList;

After that, we can create the list and add objects to it. By default, the list owns the object, which means, that the object will be freed when we remove it from the list.

FileList:= TFileInfoList.Create;
FileList.Add(TFileInfo.Create);
FileList.Add(TFileInfo.Create);
FileList.FreeObjects:= true; //list owns the objects, true is default

See documentation for more methods and functions.

Kommentar hinterlassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert