2

I am very new to the Apex programming first.And I know about Standard & Custom objects. And also the the custom objects have an extension of '__c'. I observed in the programming lot of reference about the sObject but i am not getting the concept of it clearly.

As per definitions I understood it as: sObject is a generic abstract type that corresponds to any persisted object type. The generic sObject can be cast into a specific sObject type, such as an account or the Invoice_Statement__c custom object (Standard or Custom object type).

Can someone please help me to understand more about sObject. - When, where & How it need to be used?

If possible a scenario or example to explain this will be helpful.

11

An SObject represents a specific table in the database that you can discretely query. The API Name is what you reference as ending in __c. Standard SObjects have names like Account or Opportunity, whereas Custom SObjects and Custom Settings have names like MyObject__c or MySetting__c. Custom Settings are special objects you can get without a query.

You can store any specific record in a generic SObject property. If you do so, you lose the ability to get/set most fields by name, but can get them generically.

SObject  genericAccount = new Account();
genericAccount.put('Name', 'value');

Account  specificAccount = new Account();
specificAccount.Name = 'value';
4

A common direct use of the SObject class is when writing Apex code that you want to work with various actual types e.g. something that works with Account and Contact and any other standard or custom object. For example you can call myMethod here using any type:

    Account[] accounts = ...;
    Contact[] contacts = ...;

    myMethod(accounts);
    myMethod(contacts);

public void myMethod(SObject[] sobs) {
    ...
}

but you will be limited to the methods of SObject inside myMethod. But those let you do a lot, including access all the fields and all the parent or child references.

Using SObject also allows you to write code that adapts to the objects or fields that are present - often called dynamic code. So you can write code that works whether say Person Accounts are turned off or on and that works on fields that other people have added (discovered via describe calls).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.