Icon Arrays

An array is a collection of values, all of the same type. The values in an array are referred to as the array's elements. Arrays are dynamic, meaning that their length is not specified during their declaration and can be increased or decreased at run-time, as necessary.

Array Declarations
Arrays are declared by prefacing the type name of the array with the keywords array of:

array of <Type Name>

For example, to declare a Boolean array variable, one would use the following declaration:

var
   MyBooleanArray: array of Boolean;

Please see the Variable Declarations topic for more information on declaring variables.

Getting and Setting the Length of an Array
To get the length of an array, use the Length function. Likewise, use the SetLength function to set the length of an array:

var
   MyArray: array of Integer;
begin
   SetLength(MyArray,10);
   ShowMessage(Length(MyArray)); // Displays the value 10
end;

Referencing an Array Element
Each element in an array can be accessed via its 0-based ordinal position. Square brackets directly after the array variable or parameter name are used to reference an element in an array. For example, to access the 3rd element in an array, one would use the following construct:

MyArray[2]

Warning If you try to access an element that does not exist because it is beyond the length of the array, you will cause a run-time error. Also, you must declare an array variable with a default value (see below), or use the SetLength function to set the length of an array, before attempting to reference any of the array elements. Failure to do so will result in a run-time error.

Array Constants
Just like any other variable, array variables can be initialized to a default value by specifiying an array constant as the default value in the variable declaration. This is done by enclosing a comma-delimited list of array elements in square brackets ([]):

[<Element> ,<Element>...]

In the following example the MyBooleanArray variable will be initialized to an array of Boolean elements that has a length of 3 and consists of elements that are True, False, and True, respectively:

var
   MyBooleanArray: array of Boolean = [True, False, True];

In addition to variable defaults, array constants can be used to pass array values to the parameters of functions or procedures. For example, if we want to call a procedure declared as follows:

function ListStrings(Value: array of String): String;
var
   I: Integer;
begin
   Result := '';
   for I := 0 to Length(Value) - 1 do
      begin
      if (I > 0) then
         Result := Result + ', ';
      Result := Result + Value[I];
      end;
end;

We could do so by simply passing a constant array to it, as follows:

ShowMessage(ListStrings(['These','are','some','words']);

Information The values specified for the elements in an array constant must be type-compatible with the declared type of the array.
Image