Skip to content
Generics and Containers
step 1/5

Reading — step 1 of 5

Learn

~1 min readObject Pascal Classes

FreePascal/Delphi support generic types — type-parameterized classes:

uses Generics.Collections;

var
    list: TList<integer>;
    map: TDictionary<string, integer>;
begin
    list := TList<integer>.Create;
    try
        list.Add(10);
        list.Add(20);
        list.Add(30);
        WriteLn(list[1]);              // 20
        WriteLn(list.Count);            // 3
    finally
        list.Free;
    end;

    map := TDictionary<string, integer>.Create;
    try
        map.Add('alice', 30);
        map.Add('bob', 25);
        WriteLn(map['alice']);          // 30
    finally
        map.Free;
    end;
end.

Generics.Collections provides:

  • TList<T> — dynamic array
  • TStack<T> / TQueue<T>
  • TDictionary<K, V> — hash map
  • TObjectList<T> — list that owns and frees its objects
  • TObjectDictionary<K, V> — same for dict

Define your own generic class:

type
    TBox<T> = class
    private
        FValue: T;
    public
        constructor Create(AValue: T);
        property Value: T read FValue write FValue;
    end;

constructor TBox<T>.Create(AValue: T);
begin
    FValue := AValue;
end;

Usage: TBox<integer>.Create(42) or TBox<string>.Create('hello').

Generic methods:

type
    TUtil = class
    public
        class function Max<T>(a, b: T): T;
    end;

Type constraints (specify what T must support):

type
    TBox<T: class> = class       // T must be a class type
    ...
    end;

More restrictive constraints (record, constructor, specific class) are also possible.

Generics in Pascal are monomorphized — like C++ templates, separate code per instantiation.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…