[SalesForce] Describing the Name field of a Custom Object to get Auto Number

I want to check if the (standard) Name field of an object is an auto number field or not. This can be done by describing the field and using isAutonumber()Salesforce Documentation.

I have a custom object called Project_Resource__c with a Name field set as autonumber.

The following code returns true:

Project_Resource__c.Name.getDescribe().isAutoNumber();

In a test factory class, I have a piece of code that does operations on an sObject, this can be any object, standard or custom.
What I want to achieve is to get the Name field of that particular object and check if it is an auto number field.

I've tried the following code, but with no result:

sObject sobj;
sobj = new Project_Resource__c();
insert sobj; //my assumption is that this should fill the name with the auto number

//compile error: Expression of type Schema.SObjectTypeFields has no member named Name    
System.debug(sobj.getSObjectType().getDescribe().fields.Name.getDescribe().isAutonumber()); 


// I would have expected to see the fields here
system.debug(sobj.getSObjectType().getDescribe().fields);// Returns Fields[Project_Resource__c]

Something else I find strange (but might be unrelated) is that after the insert

system.debug(sobj.get('Name'));

returns null, while

system.debug([select name from project_resource__c]);

returns a project_resource__c with an auto number name

Best Answer

The only field you get for free without re-querying is Id, so yes, you have to query back for the Name to get the actual auto-number result. As for your describe, you don't need to get the describe from your record, you can just do:

DescribeSObjectResult describe = SObjectType.Project_Resource__c;
Map<String, SObjectField> fields = describe.fields.getMap(); // <- you're missing this call
DescribeFieldResult nameDescribe = fields.get('Name').getDescribe();

Note that you can get the field describe even more simply, as you have found near the top of your OP:

DescribeFieldResult nameDescribe = Project_Resource__c.Name.getDescribe();