Reputation: 3278
I need to free list of objects stored in an ArrayList. I know you can call Free procedure in Delphi, but in Delphi Prism there is no free procedure. I don't just want to remove objects from the list but also free it from its memory.
For instance Say I have this following class
TheClass = Class
private
theStr:String;
protected
public
end;
method TheForm;
begin
TheArrayList:=new ArrayList;
end;
To Add Object I would do this:
method TheForm.AddToList;
var
tmpObj:TheClass;
begin
tmpObj := new TheClass;
TheArrayList.Add(tmpObj);
end;
To Delete Object from the list, this is how I would do it but there is no free procedure.
method TheForm.DeleteFromList;
var I:integer;
begin
for I:=0 to theArrayList.count-1 do
begin
theClass(theArrayList[I]).free; <-------I know this doesnt work.
theArrayList.RemoveAt(I);
end;
end;
end;
How is freeing list of object accomplished in Delphi Prism?
Thanks,
Upvotes: 2
Views: 691
Reputation: 28806
Delphi Prism programs run on .NET. There is no need to free any objects, since the garbage colleector will eventually do that. As someone already commented, you can call IDisposable.Dispose() to free other resources than memory, if the object implements it.
There is also the using construct, which is a bit like Create-try-finally-Free-end in Delphi:
using MyArrayList = new ArrayList do
begin
// use ArrayList...
end; // IDisposable(ArrayList).Dispose is called, if applicable.
This won't work for the items in the array, of course. If you really want, you can call Dispose on each of them. But generally, this is not necessary.
So:
method TheForm.DeleteFromList;
begin
theArrayList.Clear;
end;
No need to free anything.
Upvotes: 1
Reputation: 612794
Since your class is not holding onto any unmanaged resources like files, window handles, database connections etc. you need do nothing beyond letting the .net garbage collector free the memory when it decides the time is right.
Trying to force the garbage collector to run ahead of time typically leads to worse performance than simply letting it do its job.
If you had a class with unmanaged resources then you should follow the IDisposable pattern.
Upvotes: 4
Reputation: 2797
while theArrayList.count > 0 do
theArrayList.RemoveAt(0);
GC will help you.
Upvotes: 1