+ 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.