Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return array from a Delphi function?

Tags:

arrays

delphi

I have a function in my application that needs to return an array. I have found in a couple of places how to do this by declaring the array type, e.g.

type   TStringArray = array of string;  

And then declaring my function

function SomeFunction(SomeParam: Integer): TStringArray; 

My problem is trying to set this up in a form that has both interface and implementation. How do I declare my type and have a function declaration with that type in the interface ?

like image 305
Joe Avatar asked May 26 '11 22:05

Joe


People also ask

How do I return an array from a function in Delphi?

unit Unit1; interface uses SysUtils; type TStringArray = array of string; function SomeFunction(SomeParam: integer): TStringArray; ... implementation function SomeFunction(SomeParam: integer): TStringArray; begin SetLength(result, 3); result[0] := 'Alpha'; result[1] := 'Beta'; result[2] := 'Gamma'; end; ...


2 Answers

unit Unit1;  interface  uses SysUtils;  type   TStringArray = array of string;  function SomeFunction(SomeParam: integer): TStringArray;  ...  implementation  function SomeFunction(SomeParam: integer): TStringArray; begin   SetLength(result, 3);   result[0] := 'Alpha';   result[1] := 'Beta';   result[2] := 'Gamma'; end;  ...  end. 

The golden rule is that the interface section of a unit describes the data types used by the unit, and the types, classes and functions (their signatures) that reside in the unit. This is what all other units see. The implementation section contains the implementation of the classes and functions. This is not visible to other units. Other units need to care about the interface of the unit, the 'contract' signed by this unit and the external unit, not the 'implementation details' found in the implementation section.

like image 118
Andreas Rejbrand Avatar answered Oct 06 '22 04:10

Andreas Rejbrand


If you Delphi is fairly recent, you don't need to declare a new type, by declaring it as TArray<String>.

Example copied and pasted from the answer above:

unit Unit1;  interface  function SomeFunction(SomeParam: integer): TArray<String>;  implementation  function SomeFunction(SomeParam: integer): TArray<String>; begin   SetLength(result, 3);   result[0] := 'Alpha';   result[1] := 'Beta';   result[2] := 'Gamma'; end;  end. 
like image 28
Wouter van Nifterick Avatar answered Oct 06 '22 03:10

Wouter van Nifterick