1

I seem to be missing something obvious, but haven't been able to find anything in the Apex documentation or Trailhead modules or several web searches, including here. (The examples I've found all show the queries returning the List, but nothing following accessing the individual fields returned.) This is a greatly simplified version of what I'm really trying to do for purposes of asking the question here.

I'm executing the below in an anonymous window. I'm getting 10 contacts, then writing the ID's of each to the debug log.

List<SObject> conts = [SELECT Id,Name FROM Contact LIMIT 10];
for (SObject cont : conts) {
    System.debug('Cont is ' + cont.Id;
}

What I want to do is write the name of each of the contacts. But changing cont.Id to cont.Name on the System.debug line doesn't work, it says it's not a valid variable.

List<SObject> conts = [SELECT Id,Name FROM Contact LIMIT 10];
for (SObject cont : conts) {
    System.debug('Cont is ' + cont.Name;
}

Line: 7, Column: 36

Variable does not exist: Name

But the debug log shows this variable assignment. It has both the Id and the Name.

19:02:19:009 VARIABLE_ASSIGNMENT [6]|cont|{"Id":"0034N00001pc6T2QAI","Name":"John Doe","RecordTypeId":"01261000000X007AAC"}|0x692d38c6

So, if I requested the Name field, and the Name field is in the object variable, why do I get an error trying to access it?

(I'm using SObject on the List instead of Contact for a reason; in what I'm really doing, I don't have a choice but to use SObject.)

1 Answer 1

1
for (SObject cont : conts) {
    System.debug('Cont is ' + ((Contact)cont).Name;
}

or

for (Contact cont : (Contact[])conts) {
    System.debug('Cont is ' + cont.Name;
}

or

 for (SObject cont : conts) {
     System.debug('Cont is ' + cont.get('Name'));
 }

You need to cast the SObject to a concrete object to resolve specific field names for the compiler (examples 1 and 2) or use an sobject method (example 3)

3
  • In the real world problem, I don't know the object type, so #3 it is. Thanks very much!
    – vr8ce
    Oct 3, 2019 at 4:21
  • If I should add an edit to the question instead of this, let me know and I'll delete this.
    – vr8ce
    Oct 3, 2019 at 4:49
  • No need to edit.
    – cropredy
    Oct 3, 2019 at 4:58

You must log in to answer this question.

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