Generic sObjects in Salesforce
Chapter Topics
- Apex Data Types
- Integer Data Type in APEX
- Floating Point Data Type in APEX
- String Data Type in APEX
- Date Datatypes in APEX
- Time and DateTime Data Types in APEX
- Boolean Datatype in Salesforce
- ID & Blob Datatypes in APEX
- What is the Rule of Conversions in Apex?
- Enums in APEX
- sObjects in Salesforce
- Generic sObjects in Salesforce
- Collections in APEX
- Lists in APEX
- List Array Notation in APEX
- Lists Initialization in APEX
- Nested Lists in APEX
- Sets in APEX
- Sets Initialization And Methods
- Maps in APEX
- Map Initialization Methods in APEX
- Operators in Apex and Their Types
- Shorthand Operator
- Equality Operator
- Relational Operators(<,>,<=,>=)
What Is Salesforce Generic sObject?
Generally, while programming we use a specific sObject type when we are sure of the instance of the sObject but whenever there comes a situation when we can get an instance of any sObject type, we use generic sObject.
Generic sObject data type is used to declare the variables which can store any type of sObject instance.
For example:
sObject s1 = new Account(Name = ‘Disney’);
sObject s2 = new Contact(lastName = ‘Sharma’);
sObject s3 = new Student__c(Name = ‘Arnold’);
sObject Variable —> Any sObject Datatype instance
Note:
Every Salesforce record is represented as a sObject before it gets inserted into the database and also if you retrieve the records already present in the database they are stored in the sObject variable.
Methods to be used in Generic SObject:
We can also cast the generic sObjects in specific sObjects like this:
Account acc = (Account) s1;
Contact con = (Contact) s1; //Will throw a Runtime Exception: datatype mismatch
1. Setting and Accessing values from Generic sObjects:
Similar to the sObject, we can also set and access values from Generic sObject. However, the notation is a little different.
Examples of setting the values and accessing them:
2. Set a field value on an sObject
sObject s = new Account();s.put('Name', 'Cyntexa Labs');
3. Access a field on a sObject
Object objValue = s.get('Name');

Join our newsletter: Get daily update on Salesforce career insights & news!
Join Now!
Need more support?
Get a head start with our FREE study notes!
Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.