Optional chaining – change

apexcoderelease

I have code in production for many months and it start to be problematic.
this code involve if condition with Optional chaining.

Here is an example

List<case> cases = [Select id, Status__c FROM Case WHERE Id = '500********'];

for(Case c: cases ){
    system.debug(c?.Status__c?.Contains('Released'));
    if(c?.Status__c?.Contains('Released')){ // get the Error on this line
            System.debug('Contains');
    }
    
       if(!c?Status__c?.Contains('Released')){
            System.debug('not Contains');
    }
}

I get an error of null pointer exception in the first condition even if the exact same code return null without any issue line before.

does someone have any clue why this is happening ?

Best Answer

The safe navigation operator still returns null if a null is in the path, so you have to check for that:

if(c?.Status__c?.Contains('Released') == true){ // get the Error on this line
        System.debug('Contains');
}

Or, in an even modern alternative, you can use the null-coalescing operator:

if(c?.Status__c?.contains('Released') ?? false) {
    System.debug('Contains');
}

The main point is that ?. can return null, but a condition always expects true or false. The null-coalescing operator can help in these situations.

Related Topic