Understanding Generic Types in Delphi

Learn how to parametrize your records and types

Over the shoulder view of man programming on computers at creative office
Maskot / Getty Images

Generics, a powerful addition to Delphi, were introduced in Delphi 2009 as a new language feature. Generics or generic types (also know as parametrized types), allow you to define classes that don't specifically define the type of certain data members.

As an example, instead of using the TObjectList type to have a list of any object types, from Delphi 2009, the Generics. Collections unit defines a more strongly typed TObjectList.

Here's a list of articles explaining generic types in Delphi with usage examples:

What and Why and How on Generics in Delphi

Generics with Delphi 2009 Win32

Generics are sometimes called generic parameters, a name which allows to introduce them somewhat better. Unlike a function parameter (argument), which has a value, a generic parameter is a type. And it parameterizes a class, an interface, a record, or, less frequently, a method ... With, as a bonus, anonymous routines and routine references

Delphi Generics Tutorial

Delphi tList, tStringList, tObjectlist or tCollection can be used to build specialized containers, but require typecasting. With Generics, casting is avoided and the compiler can spot type errors sooner.

Using Generics in Delphi

Once you’ve written a class using generic type parameters (generics), you can use that class with any type and the type you choose to use with any given use of that class replaces the generic types you used when you created the class.

Generic Interfaces in Delphi

Most of the examples I’ve seen of Generics in Delphi use classes containing a generic type. However, while working on a personal project, I decided I wanted an Interface containing a generic type.

Simple Generics Type Example

Here's how to define a simple generic class:

type
TGenericContainer<T> = class
Value : T;
end;

With the following definition, here's how to use an integer and string generic container:

var
genericInt : TGenericContainer<integer>;
genericStr : TGenericContainer<string>;
begin
genericInt := TGenericContainer<integer>.Create;
genericInt.Value := 2009; //only integers
genericInt.Free;

genericStr := TGenericContainer<string>.Create;
genericStr.Value := 'Delphi Generics'; //only strings
genericStr.Free;
end;

The above example only scratches the surface of using Generics in Delphi (does not explain anything though - but above articles have it all you want to know!).

For me, generics were the reason to move from Delphi 7 / 2007 to Delphi 2009 (and newer).