Generics dan For Loop


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;

Diterbitkan oleh wisnuwidiarta

Hi, my name is Wisnu Widiarta. I am a movie lover and love traveling especially camping and doing outdoor activities. Coding and problem solving in general are things I love as well.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout /  Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout /  Ubah )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d blogger menyukai ini: