0

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 : '';

1 Answer 1

2

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.

1
  • 1
    Using parentheses around ternaries improves readability IMO even when it's not technically necessary. Jul 22, 2017 at 1:09

You must log in to answer this question.

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