How to check if a dynamic array is empty

I have a procedure declared like this:

procedure MyProc(List: Array of string); 

I want to know how to check if the List parameter is empty.

For example:

 procedure MyProc(List: Array of string); begin if List=[] then // here I want to check if the List array is empty //do something else //do something else end; 

How can i do this?

+8
arrays delphi
source share
3 answers

you can use the Length function

 procedure MyProc(List: Array of string); begin if Length(List)=0 then // is empty ? //do something else // do something else end; 
+22
source share

Empty arrays are nil :

 if List = nil then // it empty 

(This also means that SetLength(List, 0) and List := nil are equivalent commands.)

Empty arrays have the last index, which is less than the first index, which for the open array in your example means the presence of a negative last index:

 if High(List) < 0 then // it empty 

This means that if you want to avoid starting a loop in an empty array, you do not need to do anything special. Just write the loop as usual:

 for i := Low(List) to High(List) do // won't run if List is empty 
+7
source share

Personally, I always write

 if Assigned(List) then 

but not

 if List<>nil then 

because I believe that it reads better, and not just for dynamic arrays.


Answers the question about dynamic arrays, but your example is an open array, so there are two possible questions here.

For open arrays, I would use Length() or high() to make a decision based on the size of the array. I would not be tempted by the arguments that Pointer(List)<>nil faster than Length(List)<>nil . The difference in speed between these parameters will not be distinguishable, so you should use the most understandable and understandable option.

+3
source share

All Articles