- DelphiTools - https://www.delphitools.info -

Poll: dynamic arrays as reference or value type?

Here is a small poll to help me decide in which direction to go about dynamic arrays in DWScript. The poll is at the bottom of the post, to encourage reading before voting 😉

The Problem

In Delphi, fixed-size arrays behave as value types, while dynamic arrays behave as reference type, this can be illustrated by:

type
   TFixedSizeArray = array [0..9] of Integer;
   TDynamicArray = array of Integer;
...
procedure SomeProc(fixed : TFixedSizeArray; dynamic : TDynamicArray);
begin
   fixed[0]:=2;
   dynamic[0]:=2;
end;
...
var
   f : TFixedSizeArray;
   d : TDynamicArray;
begin
   f[0]:=1;
   SetLength(d, 10);
   d[0]:=1;
   SomeProc(fixed, dynamic);
   // at this point f[0] is still 1, but d[0] is now 2
end;

However if you change SomeProc to

procedure SomeProc(fixed : TFixedSizeArray; dynamic : TDynamicArray);
begin
   fixed[0]:=2;
   SetLength(dynamic, 20);
   dynamic[0]:=2;
end;

then d[0] will be unchanged, as the SetLength() call will have spawned a different dynamic array, if you want to resize a dynamic array you have to pass it as a var parameter, while if you only want to change the items, you don’t…

With current Delphi syntax, dynamic arrays are schizophrenic: they are passed by reference, like a TObject would be, but resized as value types.

In a way, dynamic arrays borrow the String type’s SetLength() syntax and behavior, but String is passed in a form that mimics a value type, in the example above, it would behave like TFixedSizeArray, ie. if you modify a String that wasn’t passed as var in SomeProc(), the original variable won’t be changed.

The Options

To rationalize the situation, there are two options:

So, what would feel more natural to you?

Dynamic arrays would be better as...

  • a value type, like non-dynamic arrays, minimize the surprise factor (38%, 22 Votes)
  • a full self-respecting reference type, more practical and efficient (62%, 36 Votes)

Total Voters: 58

Loading ... Loading ...