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.)