I am trying to use Navigation Operator. But not getting how to use it for this situation.

I want to do something like this

if ( Account != null && Account.xyz__c != null && Account.xyz__c.myField__c 
     != null) {
       // Do something

I am looking on docs. But everywhere I am finding this for 1 level.

Thanks in advance!

1 Answer 1


sObject field references have always acted as a Safe Navigation Operator (SNO):

Contact testContact = new Contact();
String accountOwnerName = testContact.Account.Owner.Name; // is null, not NullPointerException

If you need to use a non-sObject, you can chain the SNO indefinitely:

String result = source?.field1?.field2?.toLowerCase();

If at any point there would be a NullPointerException, you just get a null back.

In your example, assuming you didn't want to simply use the sObject "magic", you can:

if(Account?.xyz__r?.myField__c != null) {

But in reality, sObject references are safe until you try to call a method, so you can still just:

if(Account.xyz__r.myField__c != null) {

The most usual reason to use SNO is after deserializing JSON or XML and you're not sure intermediate objects may or may not be null.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .