// *** before: ***
// a typed list was written by hand around TObjectList: a cast on every
// read, and nothing stopped you from adding the wrong object
type
TPersonList = class(TObjectList)
private
function GetItem(Index: Integer): TPerson;
public
property Items[Index: Integer]: TPerson read GetItem; default;
end;
function TPersonList.GetItem(Index: Integer): TPerson;
begin
Result := TPerson(inherited Items[Index]);
end;
// *** in version 2009: ***
uses
Generics.Collections;
type
// your own generic type: one declaration serves every element type
TBox<T> = record
Value: T;
function IsEmpty: Boolean;
end;
var
People: TList<TPerson>;
Ages: TDictionary<string, Integer>;
begin
People := TList<TPerson>.Create;
People.Add(TPerson.Create('Anna'));
Writeln(People[0].Name); // no cast - the compiler knows the type
// People.Add(42) does not compile any more
Ages := TDictionary<string, Integer>.Create;
Ages.Add('Anna', 31);
Writeln(Ages['Anna']);
end;