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:


  { TFileInfo }

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

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

  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.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.