I'm trying to access a field from a list of sObjects which holds 3 different objects types.

List<SObject> data  = new List<SObject>();

for (sObject li : data) {
    String sObjName = li.Id.getSObjectType().getDescribe().getName();

    if(String.valueOf(sObjName) == 'CR_Contract__c'){
        Month = li.End_Date__c.month(); //Cannot access End_Date__c field
        MonthN = String.valueOf(month);

How can I access the field to run logic?


There's a better way: the switch statement. You can now do this:

for(sObject li : data){
  switch on li {
    when CR_Contract__c cr {
      Month = cr.End_Date__c.month();
    when ... {
      // etc

This new switch statement will help avoid typos as well, because they will be caught at compile-time.

  • oo i'll give that a shot now. – ridwan Jun 14 '18 at 17:52
  • Surprising the when TypeName VariableName mechanism is there: hardly seems like a pressing need. – Keith C Jun 14 '18 at 19:52
  • @KeithC I've already used it like 4 times this week, and I have like 2 or 3 dozen other near-future uses for it, too. It might seem trivial at first, but once you need it, you'll understand. – sfdcfox Jun 14 '18 at 19:54

I think I got it. I need to convert it to the type of sObject it is before I can access it.

if(String.valueOf(sObjName) == 'CR_Contract__c'){
    CR_Contract__c con = (CR_Contract__c)li;
    Month = con.End_Date__c.month();
    MonthN = String.valueOf(month);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.