Looping over a list of sObjects that has more than object type

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?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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);

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x