Pascal generics
last modified November 19, 2026 Free Pascal 3.2.2
A generic routine or type is written once and used with many element types. The
compiler produces a specialized version for each type argument, so a
TList<Integer> stores integers without casts and without
storing them as TObject. This article starts with a generic
function, then a generic record and class, and only then uses the containers
from Generics.Collections. Along the way it explains the
specialize keyword that ObjFPC mode requires.
A generic function
A generic function is declared with generic function and a type
parameter in angle brackets. The parameter behaves like a type inside the
routine and is replaced by a concrete type at each call. In ObjFPC mode the
call site names the type argument after specialize.
program genfunc;
{$mode objfpc}{$H+}
generic function MaxOf<T>(const A, B: T): T;
begin
if A > B then
Result := A
else
Result := B;
end;
begin
WriteLn(specialize MaxOf<Integer>(3, 7));
WriteLn(specialize MaxOf<Double>(2.5, 1.5):0:1);
WriteLn(specialize MaxOf<string>('apple', 'pear'));
end.
MaxOf<Integer> compares integers, and
MaxOf<string> compares strings with the normal Pascal string
comparison. There is no runtime type check and no boxing: each specialization is
ordinary compiled code. A type that does not support > produces
a compile-time error at the specialization, not at run time.
$ fpc -gl genfunc.pas $ ./genfunc 7 2.5 pear
A generic record
A record can be generic in the same way. generic TPair<T>
declares two fields of the same parameter type, and
specialize TPair<Integer> produces a concrete record with two
integer fields. The string specialization is a different type with different
storage.
program pair;
{$mode objfpc}{$H+}
type
generic TPair<T> = record
First, Second: T;
end;
var
Numbers: specialize TPair<Integer>;
Names: specialize TPair<string>;
begin
Numbers.First := 10;
Numbers.Second := 32;
WriteLn('sum = ', Numbers.First + Numbers.Second);
Names.First := 'Alice';
Names.Second := 'Bob';
WriteLn(Names.First, ' and ', Names.Second);
end.
The two variables have no relationship at run time: Numbers is a
record of two integers, and Names is a record of two strings.
Assigning one to the other is a compile-time error. A generic record keeps the
value semantics of an ordinary record, so it is copied field by field and needs
no constructor or destructor.
$ fpc -gl pair.pas $ ./pair sum = 42 Alice and Bob
A generic class of your own
A generic class is declared with generic before its name and a type
parameter in angle brackets. The parameter can appear in fields, parameters,
properties, and result types. A concrete type is produced with
specialize and a type argument.
program box;
{$mode objfpc}{$H+}
type
generic TBox<T> = class
private
FValue: T;
public
constructor Create(AValue: T);
function GetValue: T;
procedure SetValue(AValue: T);
end;
constructor TBox.Create(AValue: T);
begin
FValue := AValue;
end;
function TBox.GetValue: T;
begin
Result := FValue;
end;
procedure TBox.SetValue(AValue: T);
begin
FValue := AValue;
end;
type
TIntBox = specialize TBox<Integer>;
TStringBox = specialize TBox<string>;
var
I: TIntBox;
S: TStringBox;
begin
I := TIntBox.Create(42);
WriteLn('integer box: ', I.GetValue);
I.SetValue(99);
WriteLn('after set: ', I.GetValue);
I.Free;
S := TStringBox.Create('Pascal');
WriteLn('string box: ', S.GetValue);
S.Free;
end.
The same source produces two classes: one whose FValue is an
Integer and one whose FValue is a
string. The compiler specializes the methods, so
GetValue returns the right type without a cast. Naming the
specializations TIntBox and TStringBox keeps the
declarations readable, especially when the type is used in several places.
$ fpc -gl box.pas $ ./box integer box: 42 after set: 99 string box: Pascal
Constraints
A type parameter can be constrained to a family of types. The constraint
T: class allows the generic code to call methods that every class
has, such as Free and ClassName. A constraint is
checked when the generic type is specialized, and a type argument that does not
satisfy it is a compile-time error.
program constraint;
{$mode objfpc}{$H+}
uses Classes;
type
generic TBox<T: class> = class
private
FValue: T;
public
constructor Create(AValue: T);
destructor Destroy; override;
function ClassNameOfValue: string;
end;
constructor TBox.Create(AValue: T);
begin
FValue := AValue;
end;
destructor TBox.Destroy;
begin
FValue.Free;
inherited Destroy;
end;
function TBox.ClassNameOfValue: string;
begin
Result := FValue.ClassName;
end;
type
TObjectBox = specialize TBox<TObject>;
var
B: TObjectBox;
begin
B := TObjectBox.Create(TStringList.Create);
try
WriteLn('stored: ', B.ClassNameOfValue);
finally
B.Free;
end;
end.
The destructor can call FValue.Free only because the constraint
promises that T is a class. Without the constraint, the compiler
cannot know that the value has a Free method. The box owns the
object it stores, so the caller creates the list but does not free it; the box's
destructor does.
$ fpc -gl constraint.pas $ ./constraint stored: TStringList
A list from the standard library
Generics.Collections provides ready-made containers, including
TList<T>, TDictionary<K,V>,
TQueue<T>, and TStack<T>. A type alias
keeps the specialization out of every declaration. The next program stores
integers, sorts them, and reads them by index.
program listtest;
{$mode objfpc}{$H+}
uses SysUtils, Generics.Collections;
type
TIntList = specialize TList<Integer>;
var
Numbers: TIntList;
I: Integer;
begin
Numbers := TIntList.Create;
try
Numbers.Add(30);
Numbers.Add(10);
Numbers.Add(20);
WriteLn('count = ', Numbers.Count);
Numbers.Sort;
for I := 0 to Numbers.Count - 1 do
begin
if I > 0 then
Write(' ');
Write(Numbers[I]);
end;
WriteLn;
WriteLn('first = ', Numbers.First);
finally
Numbers.Free;
end;
end.
Add, Count, the indexed property, and
Sort are the same operations a non-generic list would have, but the
element type is fixed at compile time. The list is a class, so it is created with
Create and released with Free; the
try..finally block guarantees the release if an exception is
raised. First returns the element at index 0.
$ fpc -gl listtest.pas $ ./listtest count = 3 10 20 30 first = 10
The Delphi spelling
Free Pascal has two syntaxes for generics. In ObjFPC mode, a type argument must
be introduced with specialize. In Delphi mode, the same type is
written without the keyword, as in TList<string>. Both forms
produce the same code; the difference is a dialect convention, not a runtime
feature.
program delphilist;
{$mode delphi}{$H+}
uses SysUtils, Generics.Collections;
var
Names: TList<string>;
Name: string;
begin
Names := TList<string>.Create;
try
Names.Add('Alice');
Names.Add('Bob');
Names.Add('Caroline');
for Name in Names do
WriteLn(Name);
WriteLn('contains Bob: ', Names.Contains('Bob'));
finally
Names.Free;
end;
end.
The for..in loop works because the list provides an enumerator, the
same mechanism that the loops article used for
strings and arrays. A single source file can use either mode, but a unit that
exports generic types should document which spelling its callers need. Mixing
the two in one project is possible; mixing them in one declaration is not.
$ fpc -gl delphilist.pas $ ./delphilist Alice Bob Caroline contains Bob: TRUE
A dictionary
TDictionary<TKey, TValue> maps keys to values. It stores one
value per key, supports lookup with TryGetValue, and enumerates its
keys. The next program maps names to scores. Because a dictionary does not
promise an order, the keys are copied to a TStringList and sorted
before they are printed.
program dict;
{$mode objfpc}{$H+}
uses SysUtils, Classes, Generics.Collections;
type
TScoreMap = specialize TDictionary<string, Integer>;
var
Scores: TScoreMap;
Score: Integer;
Key: string;
Keys: TStringList;
begin
Scores := TScoreMap.Create;
Keys := TStringList.Create;
try
Scores.Add('Alice', 92);
Scores.Add('Bob', 78);
Scores.Add('Caroline', 85);
WriteLn('count = ', Scores.Count);
if Scores.TryGetValue('Bob', Score) then
WriteLn('Bob = ', Score);
for Key in Scores.Keys do
Keys.Add(Key);
Keys.Sort;
for Key in Keys do
WriteLn(Key, ' -> ', Scores[Key]);
finally
Keys.Free;
Scores.Free;
end;
end.
TryGetValue returns False when the key is missing and
leaves the output variable unchanged; the indexer Scores[Key] reads
an existing key. Adding a key that is already present raises an exception, and
AddOrSetValue replaces the old value instead. The
hash tables article looks at the structure
that makes these operations fast.
$ fpc -gl dict.pas $ ./dict count = 3 Bob = 78 Alice -> 92 Bob -> 78 Caroline -> 85
Limitations and portability
Free Pascal specializes generics at compile time, so a generic unit must be
compiled with the same compiler version as the code that uses it. The
specialize keyword is an ObjFPC convention; Delphi mode and recent
Delphi compilers write the same type without it. Code that must compile in both
dialects needs conditional directives or a small wrapper unit for each syntax.
The standard library does not provide every generic container that other
languages have. Free Pascal's Generics.Collections includes lists,
dictionaries, queues, and stacks, while a dynamic array is already generic in
the language itself. When a container is missing, a small generic class is
usually enough; the stacks and queues
article uses the provided ones.
Next steps
The stacks and queues article uses
TStack<T> and TQueue<T>, and the
sorting article shows how a generic list is
sorted with a comparator. The interfaces
article explains the contracts that generic containers implement, and the
records article covers the value types that
generics can store.
Source
Free Pascal Run-Time Library reference
Generic programming on Wikipedia
In this article we wrote a generic function, declared a generic record and a generic class, applied a class constraint, used the standard list and dictionary containers, and compared the ObjFPC and Delphi spellings. The series continues with CSV and text data in Pascal.
Author
List all Pascal tutorials.