Generics adalah salah satu fitur baru dari RAD Studio 2009. Generic merupakan fitur penggunaan tipe data dengan parameter. Masih ingat penggunaan TList? Setiap kali kita menambahkan object di dalam TList kita harus melakukan casting setiap kali akan membacanya. Dengan generic, kita tidak perlu lagi melakukannya!
TPeople = class(TObject)
private
FName: String;
procedure SetName(const Value: String);
public
property Name: String read FName write SetName;
end;
Jadul Version (masih disupport juga lho) :
for i := 0 to peopleList.Count – 1 do
begin
ShowMessage((peopleList[i] as TPeople).Name);
end;
while peopleList.Count > 0 do
begin
peopleList[0].Free;
peopleList.Delete(0);
end;
Versi menggunakan generic (awas perlu uses Generics.Collections; )
var
peopleList: TList<TPeople>;
people: TPeople;
begin
peopleList := TList<TPeople>.Create; //deklarasi List of TPeople
people := TPeople.Create;
people.Name := ‘Wisnu’;
peopleList.Add(people);
people := TPeople.Create;
people.Name := ‘Widiarta’;
peopleList.Add(people);
for people in peopleList do //for loopnya dah keren!
begin
ShowMessage(people.Name);
people.free;
end;
peopleList.Free;
end;