[SalesForce] String null value check concatenate string

I am using below code to check string null or blank value and then concatenating field but this is not working – Can you please help..

 string result = abc__c.field1__c!=NULL ? abc__c.field1__c:''+  abc__c.field2__c != NULL ? abc__c.field2__c : '' +abc__c.field3__c != NULL ? abc__c.field3__c : '';

Best Answer

You need to use parentheses to make sure that the logic is parsed correctly:

string result = (abc__c.field1__c != NULL ? abc__c.field1__c : '')+
                (abc__c.field2__c != NULL ? abc__c.field2__c : '')+
                (abc__c.field3__c != NULL ? abc__c.field3__c : '');

The reason why is that the ternary operator is right associative, and + has a higher precedence than assignments (including ternary operators), so the default operation without parentheses looks like this:

string result = abc__c.field1__c != NULL ? abc__c.field1__c : (''+
                abc__c.field2__c != NULL ? abc__c.field2__c : (''+
                (abc__c.field3__c != NULL ? abc__c.field3__c : '')));

Which is not the intended effect.

Related Topic