1. Technology

Understanding Generic Types in Delphi

Learn how to parametrize your records and types

By

Generics, a powerful addition to Delphi, were introduced in Delphi 2009 as a new langage 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

Using New Delphi Coding Styles and Architectures
The generic type can be used as the type of a field (as I did in the previous example), as the type of a property, as the type of a parameter or return value of a function and more.

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 parameterize 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 type casting. 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 nothing 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).

©2014 About.com. All rights reserved.