Safe Navigation Operator in Apex (Winter 21 Release)

Salesforce is releasing a brand new important feature in Winter 21 release which is Safe Navigation Operator, it will useful to safely check null pointer exception.


for e.g. following code will throw null pointer exception if Contact is null.


Id contactId = Contact.Id;


to avoid null pointer exception, a null check is required. Above code can written as follows.


if(Contact!=null)

{

Id contactId = Contact.Id;

}


This new feature will let you safely check null pointer exception. Above code can be written with Safe Navigation Operator as follows.


Id contactId = Contact?.Id;


In this statement if Contact is null, then Contact.Id will not evaluated.


More example -