Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Exit with a record as result in Delphi?

Tags:

delphi

Delphi has an option to exit with a value (Example: Exit(0);), but how do I exit with a value if the return value is a record?

TIntResult = record
  Value: Integer;
  Error: String;
end;

function GetCount: TIntResult;
begin
  if not IsLoggedIn then
    Exit(Value: 0; Error: 'Not logged in'); // I want this

  if not IsAdmin then
    Exit(TIntResult(Value: 0; Error: 'Not Admin')); // or this
  ...
end;
like image 787
Георгий Пугачев Avatar asked Jan 24 '26 07:01

Георгий Пугачев


1 Answers

Of course, you can always use the Result variable and Exit.

But if you want to use the Delphi 2009+ Exit(...) syntax -- without giving it a TIntResult-typed variable --, the two most obvious options are these:

Using a constructor

type
  TIntResult = record
    Value: Integer;
    Error: string;
    constructor Create(AValue: Integer; const AError: string);
  end;

{ TIntResult }

constructor TIntResult.Create(AValue: Integer; const AError: string);
begin
  Value := AValue;
  Error := AError;
end;

Then you can do:

function Test: TIntResult;
begin
  // ...
  Exit(TIntResult.Create(394, 'Invalid page.'));
end;

Using a TIntResult-returning function

function IntRes(AValue: Integer; const AError: string): TIntResult;
begin
  Result.Value := AValue;
  Result.Error := AError;
end;

Then you can do:

function Test: TIntResult;
begin
  // ...
  Exit(IntRes(394, 'Invalid page.'));
end;
like image 102
Andreas Rejbrand Avatar answered Jan 26 '26 00:01

Andreas Rejbrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!