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
jucuzoglujucuzoglu 

Cast generic sObject without hardcoding object type

I would like to pass a string with the Object API name and build a list of that object type. For example how I wished it worked.

 

string myObjectAPIName = 'Account';
List<sObject> myGenericObjectList = new List<myObjectAPIName>();

 Thank you in advance for the assistance.

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

You can't do that I'm afraid - you can't instantiate the list based on the contents of a variable.

 

Is there a reason why you can't instantiate a list of generic sobjects and then populate that with your particular sobject type?

All Answers

bob_buzzardbob_buzzard

You can't do that I'm afraid - you can't instantiate the list based on the contents of a variable.

 

Is there a reason why you can't instantiate a list of generic sobjects and then populate that with your particular sobject type?

This was selected as the best answer
jucuzoglujucuzoglu

Good solution Bob.

 

What I ended up doing was creating a dynamic Query (for which I can pass a string of the custom object I want into) to cast my sObject and all seems well.