function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

updating a field in list of sObject

Hi ,

i have a list of sobject as 
        List<sObject> lstSObject = new List<sObject>();
i want to update a field test__c = 'abc' for all the records in this list of sObject.
i tried something like 
for(SObject so : lstSObject){
            so.test__c = so.test__c + 1;
update lstSobject;

But it throw me the error saying could not identify variable test__c. 
Can anyone please give me a snippet how to update a specific field of list of sObjects?

Raj VakatiRaj Vakati
Try this code
List<Account> so =[Select Id , Name from Account Limit 2] ;
List<Sobject> spUpdate = new List<SObject>();
for(Account s :so){
    s.Name ='Test' ;

update spUpdate ;

Hi Rajamohan, It is not list of specific object( account ,contact , custom object). I am using list of sObject . Thanks
Raj VakatiRaj Vakati
  • What try you are trying to do is not possible .. Because you can't insert data into Sobject directly . . 
  • Consider Sobject is top-level object .. where you can type cast it .. 
  •  sObject is not contains any filed test__c

Raj VakatiRaj Vakati
Narender Singh(Nads)Narender Singh(Nads)
You cannot directly update a field with an sobject type. You have to first cast that sobject to the type of object on which your custom field is.

The code will look something like this:
Account[] UpdateList= new Account[]{};
for(SObject so : lstSObject){
            Account a = (Account)so; //Here you will have to make sure your sObject is of type Account
            a.test__c = a.test__c +1
update UpdateList;