public class test {
    public sObject s = [Select name from Merchandise__c where name='pencils'];

The code is compiled successfully but when i try to execute the code from the anonymous window by using the following code:

system.debug(new test().s.Name);

i get the following error message:

Line: 1, Column: 27
Variable does not exist: Name

If instead of of the above i write the following in anonymous window:

system.debug(new test().s.id);


system.debug(new test().s);

It runs succesfully Why?


Because the generic sObject doesn't return any other field except Id using dot notation.

So if you want to get the field from sObject you need to do

s.get('Name'); //pass field API here

or better you can create a sObject instance and simply use the Dot Notation.

public Merchandise__c s = [Select name from Merchandise__c where name='pencils' LIMIT 1];
system.debug(new test().s.Name);

It is because sObject is a generic type: it has an Id, but not a name. Please change sObject in your code to Merchandise__c. That is also better practise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.