Skip to content
Delphi

Generics

Type-safe containers with generics in Delphi.

By EZ4Code Team
genericscollections

Code

uses
  System.Generics.Collections;

type
  TPair<T1, T2> = class
  private
    FFirst: T1;
    FSecond: T2;
  public
    property First: T1 read FFirst write FFirst;
    property Second: T2 read FSecond write FSecond;
    constructor Create(AFirst: T1; ASecond: T2);
  end;

// Generic collections
var
  List: TList<Integer>;
  Dict: TDictionary<string, TDateTime>;
begin
  List := TList<Integer>.Create;
  try
    List.Add(10);
    List.Add(20);
    List.Sort;  // type-safe sort
    // List.Add('text');  // compile error
  finally
    List.Free;
  end;

  Dict := TDictionary<string, TDateTime>.Create;
  Dict.Add('today', Now);
end;

Explanation

Delphi generics (since Delphi 2009) work like C++ templates. TList<T> replaces TList with pointers; TDictionary<K,V> replaces TStringList hacks. Generics provide compile-time type safety and avoid casts. Always Free generic containers (they don't own items by default).

More Delphi Snippets