Activity Forums Salesforce® Discussions Casting between the generic sObject type and the specific sObject type in salesforc

  • Casting between the generic sObject type and the specific sObject type in salesforc

    Posted by shradha jain on September 3, 2018 at 9:54 am

    What do you mean by casting  between the generic sObject type and the specific sObject type.?

    • This discussion was modified 6 years, 3 months ago by  shradha jain.
    shariq replied 6 years, 3 months ago 3 Members · 2 Replies
  • 2 Replies
  • chanchal kumar

    Member
    September 3, 2018 at 10:48 am

    When you’re dealing with generic sObjects, you sometimes need to cast your sObject variable to a specific sObject type. One of the benefits of doing so is to be able to access fields using dot notation, which is not available on the generic sObject. Since sObject is a parent type for all specific sObject types, you can cast a generic sObject to a specific sObject.

    eg.

    Account acct = (Account)myGenericSObject;
    String name = acct.Name;
    String phone = acct.Phone;

  • shariq

    Member
    September 19, 2018 at 12:16 am

    Hi,

    Example - 

    public static void dynamicUpsert(List<SObject> records)
    {
    Schema.SObjectType sObjectType = records.getSObjectType();
    if (sObjectType != null)
    {
    String listType = 'List<' + sObjectType + '>';
    List<SObject> castRecords = (List<SObject>)Type.forName(listType).newInstance();
    castRecords.addAll(records);
    upsert castRecords;
    }
    }

    Hope this helps.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos