Q:

List.Add() not working

I've got the following code snippet in a trigger handler class
x1 = trigger.new;
List<Id> listx = new List(Id);

    For(integer i = 0; i < x1.size(); i++ ) {

         System.debug('Loop run:'+ i);    

                listx.add(x1[i].Ben_Loan__r.id);

          }

System.debug('listx:' + listx );

In the debug logs, 'listx' is shown as null even though it should work. Ben_Loan__r.id is the id of a look up field.
When I try a different For Loop as below, I still get an error "Variable id does not exist". 
   For(List <Beneficiary_Loan_Repayment__c> LX1 : x1){
            listx.add(LX1.Beneficiary_Loan__r.id);
}

Any idea what the issue could be? Thanks in advance

A:

You cannot access related fields in trigger context, only fields on the object that is in transaction can be accessed. If you want to access related fields, you will have to query it explicitly. If you try to access relationship fields in trigger context, it will return null, hence your list is showing null.
In your case, as you are accessing the ID field, you can access directly using the lookup field instead of using relationship field.
You can replace this below code
listx.add(x1[i].Ben_Loan__r.id);

with 
listx.add(x1[i].Ben_Loan__c);

Similarly, you can replace below code if its a lookup field
listx.add(LX1.Beneficiary_Loan__r.id);

with
listx.add(LX1.Beneficiary_Loan__c);

