function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ralph SrRalph Sr 

How do I dynamically reference a field on an object

My subject line may not properly state what I am trying to do...

Hopefully the short code sample below makes more sense of what I am tryhing to accomplish.

List<Test_Object__c> testObject = new List<Test_Object__c>();
testObject = [SELECT Id, Field1__c, Field2__c FROM TestObject__c]
String FieldNameNeeded = 'Field1__c';
for (Test_Object__c test : testObject) {
    FieldValueNeeded = test.Field1__c; //hardcoded field name
}

How to I correctly use the variable FieldNameNeeded instead of hardcoding the fieldname?  I could not find a reference using Schema data that made sense...


Best Answer chosen by Ralph Sr
pconpcon
You can use the .get method

String fieldName = 'Field1__c';

for (Test_Object__c test: testObject) {
     String result = test.get(fieldName);
}


All Answers

pconpcon
You can use the .get method

String fieldName = 'Field1__c';

for (Test_Object__c test: testObject) {
     String result = test.get(fieldName);
}


This was selected as the best answer
Ralph SrRalph Sr
So obvious...  Sometimes the forest is too thick to see the trees!  Thank you.