Sub topic 11
SObjects as data types
This chapter assumes you know Apex primitives, variables, and List, Set, and Map collections from earlier chapters. It also assumes you have used Anonymous Apex in the Developer Console. Examples that use insert or SOQL create real records in your org, so run them in a Developer Edition org or sandbox.
What an SObject is
An SObject (short for Salesforce object) is the Apex type that represents one record of a Salesforce object. Each record type has its own Apex class, such as Account, Contact, or a custom object like Invoice__c. All of them inherit from the generic type SObject.
This gives you two ways to work with records:
| Style | Declaration | Field access | Checked at |
|---|---|---|---|
| Specific | `Account a` | `a.Name` | Compile time |
| Generic | `SObject s` | `s.get('Name')` | Run time |
Prefer the specific type. The compiler catches misspelled fields and wrong value types. Use the generic type only when the object isn't known until run time.
Creating and reading specific SObjects
The constructor accepts field values as name-value pairs. Any field you don't set holds null.
Account acc = new Account(Name = 'Acme', Industry = 'Energy');
acc.NumberOfEmployees = 250;
System.debug(acc.Name);
System.debug(acc.Phone == null);Each field has a fixed Apex type that matches its Salesforce field type. NumberOfEmployees is an Integer, so acc.NumberOfEmployees = 'ten' fails to compile. Text fields map to String, checkboxes to Boolean, currency and number fields to Decimal or Double, and date fields to Date or Datetime.
After a successful insert, Apex fills in the Id field on the same variable. Id is a primitive type that holds a record identifier.
Account acc = new Account(Name = 'Acme');
System.debug(acc.Id);
insert acc;
System.debug(acc.Id);
Id savedId = acc.Id;
System.debug(savedId.getSObjectType());The first debug prints null. The second prints the new Id. The last prints Account.
Fields that were not queried
A record returned by SOQL contains only the fields in the SELECT list, plus Id. Reading any other field throws a System.SObjectException. That is different from a field that is simply unset on a new record, which returns null.
Account acc = new Account(Name = 'Acme');
insert acc;
Account fetched = [SELECT Id FROM Account WHERE Id = :acc.Id];
try {
System.debug(fetched.Name);
} catch (SObjectException e) {
System.debug(e.getMessage());
}The message says the row was retrieved via SOQL without querying the requested field.
Null SObjects and relationships
The variable itself can be null, for example when you declare it without assigning a record. Reading a field from a null variable throws a NullPointerException. The safe navigation operator ?. returns null instead.
Contact c = null;
String accountName = c?.Account?.Name;
System.debug(accountName ?? 'No account');Relationship fields work the same way. On a Contact queried with Account.Name, c.Account is itself an Account SObject. If the contact has no parent, c.Account is null, so use ?. when the parent is optional.
Assignment copies the reference
An SObject variable holds a reference to the record data, not the data itself. Assigning one variable to another gives you two names for the same object.
Account a = new Account(Name = 'Acme');
Account b = a;
b.Name = 'Beta';
System.debug(a.Name);
Account c = a.clone(false, true);
c.Name = 'Gamma';
System.debug(a.Name);The first debug prints Beta, because a and b share one object. clone(false, true) makes an independent copy. The first argument is preserveId. Passing false gives the copy no Id, so inserting it creates a new record. The second argument is isDeepClone. Passing true also copies related child lists.
This matters when you add the same variable to a list several times in a loop. Every list entry then points at one object, and later changes overwrite earlier ones. Create a new SObject inside each loop iteration instead.
Equality between SObjects
The == operator compares SObjects by type and field values. The === operator checks whether both variables refer to the same object in memory.
Account x = new Account(Name = 'Acme');
Account y = new Account(Name = 'Acme');
System.debug(x == y);
System.debug(x === y);
System.debug(x === x);This prints true, false, true.
Generic SObjects and casting
A specific SObject converts to SObject implicitly. Converting back needs an explicit cast. A wrong cast throws a TypeException.
SObject s = new Account(Name = 'Acme');
s.put('Industry', 'Retail');
Object name = s.get('Name');
System.debug(name);
System.debug(s.getSObjectType());
Account acc = (Account) s;
System.debug(acc.Industry);
try {
Contact bad = (Contact) s;
} catch (TypeException e) {
System.debug('Wrong type');
}get returns Object, so cast it before using it as a String. put throws a SObjectException if the value doesn't match the field's type.
SObjects in collections
A List<Account> is the standard container for records you plan to insert or update together. A Map<Id, Account> can be built straight from a list. Apex uses each record's Id as the key.
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 5];
Map<Id, Account> byId = new Map<Id, Account>(accounts);
Set<Id> ids = byId.keySet();
System.debug(ids.size() == accounts.size());A List<SObject> can hold different types in one list. DML on a mixed list works, but you must cast each element before you use type-specific fields. Records that are not yet inserted have a null Id. You can't key a map by Id until after the insert.
Common errors
- NullPointerException on a field read. The SObject variable is null. Check it, or use
?.. - SObjectException about a field not queried. Add the field to the
SELECTlist. - Edits that appear on two variables. Both variables point at one object. Use
clone. - TypeException on cast. The runtime type differs from the cast type. Check
s.getSObjectType()first.
Exercise
A loop adds the same Account variable to a list ten times, changing Name before each add. After the loop, what do the ten entries contain, and how do you fix it?
Show answer
All ten entries refer to the same object, so every entry shows the last name assigned. Create the Account with new Account(...) inside each iteration, or add a clone() of it, so each list entry is a separate object.
Exercise
A query uses SELECT Id FROM Contact, and the code then reads c.Email. Does this return null or throw an exception? What would happen for new Contact() instead?
Show answer
It throws a System.SObjectException, because Email was not in the SELECT list. For new Contact(), reading Email returns null, because the field is simply unset.