PDA

View Full Version : How to check for a null object?



slenkar
13-11-2010, 11:21 PM
If I have an array of objects, how do I check if an object exists at part of the array?

I tried if object=null but it said i need a 'variant'

chronozphere
14-11-2010, 01:05 AM
var
Arr: array [0..5] of TObject;
begin
//Stuff here....

for i:=0 to high(Arr) do
if Arr[i] = nil then
ShowMessage( Format('Position %d is NIL.', [i]) );
end;


(lol, thumbsdown icon was accidental.. srry. ;) )

User137
14-11-2010, 01:24 AM
Just little details to add:

If you do this to free item, arr[3] will not be nil
arr[3].Free;

These 2 are the recommended ways:
FreeAndNil(arr[3]);
or
arr[3].Free;
arr[3]:=nil;
----
If you use neither of the 2 methods to nil it, then you might try this check:
If Assigned(arr[3]) then // object exists
// But if it was Freed before without nil i don't really know if there is a chance to AV or misinformation

However Assigned() is slower than if you'd simply check the nil.

slenkar
14-11-2010, 06:17 PM
thanks both, I think im ready to do memory management now (?)