Identify differences between a parameter by value and by reference

Completed

You can pass parameters by value or by reference. Each method provides different benefits.

Pass parameters by value

When you pass a parameter by value, you're passing the value of a variable to a procedure. This method is always the case by default with fundamental types.

In the next example, the function MyFunction gets a parameter of type integer, changes the value, and returns the value of paramA. The Exit statement returns the value.

trigger OnRun()
var
    myInteger : Integer;
    myResult : Integer;
begin
    myInteger := 23;
    myResult := MyFunction(myInteger);

    Message('myInteger: %1', myInteger);  // Displays 23
    Message('myResult: %1', myResult);    // Displays 17
end;

procedure MyFunction(paramA : Integer) : Integer
begin
  paramA := 17;
  Exit(paramA);
end;

The value of myInteger remains at 23, even after the MyFunction procedure has run.

Pass parameters by reference

A variable always allocates a certain part of computer memory. When you pass a parameter by reference, you aren't passing the value to a procedure but rather to the reference, which is its position in memory. By using this method, you're working directly in memory. As a result, changing that value has an impact in your calling procedure as well. To pass a parameter by reference, you need to add the var keyword in front of a parameter.

trigger OnRun()
var
    myInteger : Integer;
    myResult : Integer;
begin
    myInteger := 23;
    myResult := MyFunction(myInteger);

    Message('myInteger: %1', myInteger);  // Displays 17
    Message('myResult: %1', myResult);    // Displays 17
end;

procedure MyFunction(var paramA : Integer) : Integer
begin
  paramA := 17;
  exit(paramA);
end;

Returning complex types

You can now simplify your AL code and return complex types, instead of passing these in the method parameters.

As an example, the following method takes a name and return the first customer record that matches the name. Notice how the signature specifies the return type at the end of the procedure declaration, and how the procedure exits by returning the found customer record.


procedure GetCustomerByName(Name: Text): record Customer;
var
    Customer: record Customer;
begin
    Customer.SetFilter(Name, '@' + Name + '*');
    Customer.FindFirst();
    exit(Customer);
end;

You can use this new feature to call members directly on the returned variable, for example, in expressions.

As an example, you could use the above in an IF statement such as
if GetCustomerByName('SomeName')."Balance (LCY)" > 0 then.

More examples of returning complex types are available here:

Return of the Complex Type