Joe
Joe

Reputation: 1009

How to return array from a Delphi function?

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 ?

Upvotes: 30

Views: 53258

Answers (2)

Andreas Rejbrand
Andreas Rejbrand

Reputation: 109003

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.

Upvotes: 42

Wouter van Nifterick
Wouter van Nifterick

Reputation: 24116

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.

Upvotes: 21

Related Questions