Tuesday, 11 March 2014

Generic Types in Delphi

Generic Types in Delphi

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.

Simple Generics Type Example in Delphi

Here's how to define a simple generic class:

  TGenericContainer<T> = class
  Value : T;

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

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

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

No comments:

Post a Comment