It might seem boring to discuss about this, but passing variables By Value vs By Reference in NAV AL (as in other languages) does not always behave the same (depending on the type of variable). In this post I will explain the differences as this is an important thing to understand.
Let’s compare passing a Record to passing an AL List:
ModifyRecordByReference: because the value from Cust was not copied to pCust, but was passed as a reference, now both variables refer to the same memory address. So any modification done to the pCust will be reflected also in Cust.
This is the standard way of doing things in NAV when working with records, it should not be something new or “strange” for any Nav developer.
Now let’s see what happens if we do the SAME thing using a List instead of a Record:
What value do you think we will have in List1 after function ModifyListByValue is called ? If the answer is ‘CustomerName’ (the initial value) then you are wrong.
ModifyListByValue: when we instantiate the List1 an object is created in memory and variable List1 stores only a reference to that object. When we pass the reference by value to the function ModifyListByValue, a copy of that reference is created, but it points to the same object that List1 points to as well. So the modification we did to pList1 is reflected also in List1.
So, when using an AL List (and any other Reference Type) you don’t have to pass the argument by reference if you want the modifications done in the called function to be reflected in the initial variable. Also, be aware that even if you pass the argument by value, the modifications affect also the initial variable. In case you don’t want this, you will need to create a new instance of the object. (for example copy the data from the list to another list).
If it is not clear, please read more about this subject here.
Furthermore, when passing temporary records as arguments you need to be aware of some things too. These were explained in this post.