-1

I am new to Apex so kindly help

{
    public static void showAccountsName()
    {
        List<sObject> AccountsList = new List<sObject>();
        AccountsList = [Select name from Account];
        for(sObject accCurrent : AccountsList)
        {
            System.debug(accCurrent.Name);
        }
     }
    
}

The Above code shows an error as  **Variable does not exist: Name**


public class CreateClass
{
    public static void showAccountsName()
    {
        List<sObject> AccountsList = new List<sObject>();
        AccountsList = [Select name from Account];
        for(sObject accCurrent : AccountsList)
        {
            System.debug(accCurrent.get('Name'));
        }
}

The above code works fine, What could be the possible reason. Thanks in Advance.
    

2 Answers 2

2

The base SObject API, extended by all the specific object types, does not include the Name property since not every single SObject in Salesforce has a Name (though most do).

You have two choices here:

  1. Continue treating the returned data as SObject and use the SObject.get() function to read a named field, like you do in the second example.
  2. Treat the result of the query as the actual SObjects they are, here Account.

Generally speaking option 2 is better as you get type safety and "compile time" checking that referenced fields exist.

Update the code like:

        List<Account> accounts = [SELECT Name FROM Account];

        for (Account accCurrent : accounts) {
            System.debug(accCurrent.Name);
        }
0

Here is the possible reason why error code doesn't actually run

In salesforce we do have around 399 standard object where some it doesn't have name field. So when you try to get sObject.name, it is actually checking other standard object as well which doesn't have name field.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .