In this Blog Post, you will learn how to fix the Salesforce Apex error “Invalid constructor syntax, name=value pairs can only be used for SObjects” when instantiating Location records.
When developing in Salesforce Apex, you may encounter a compile-time error that leaves you scratching your head: Invalid constructor syntax, name=value pairs can only be used for SObjects.
This error typically triggers when you attempt to instantiate an SObject using field assignment syntax inside the constructor, but Apex misinterprets your code as referencing a system class instead of a database object.
Here is a breakdown of why this happens and how to resolve it quickly.
Understanding the Root Cause
Salesforce includes a built-in System class named System.Location (used for geographic coordinates like latitude and longitude) as well as a standard SObject named Location (used for physical locations like warehouses, stores, or offices).
When you write new Location(...), Apex defaults to the built-in System.Location class rather than the Schema.Location SObject. Because System.Location is an Apex class and not a database SObject, Apex does not allow name=value pair field assignments inside its constructor—leading directly to the error.
The Error in Action
Consider the following Apex code snippet:
insert new Location(
Name = 'Test Warehouse',
LocationType = 'Warehouse'
);
Executing this code results in the following compilation failure:
Line: 1, Column: 8
Invalid constructor syntax, name=value pairs can only be used for SObjects: System.Location
The Resolution
To tell the Apex compiler explicitly that you are instantiating the database SObject rather than the System class, prepend the Schema namespace to your object declaration:
insert new Schema.Location(
Name = 'Test Warehouse',
LocationType = 'Warehouse'
);
By explicitly specifying Schema.Location, Apex correctly identifies the target as an SObject and allows field-level name=value pair constructor assignments.
Recommendations & Best Practices
- Explicit Namespace Prefixing: Whenever an SObject shares a name with an Apex System class (e.g.,
Location,Group,User), always explicitly prefix the SObject declaration withSchema.to prevent namespace collision. - Alternative Instantiation: If you prefer avoiding the
Schema.prefix, you can instantiate the SObject using standard property assignment before inserting:
ApexLocation loc = new Location(); loc.Name = 'Test Warehouse'; loc.LocationType = 'Warehouse'; insert loc;(Note: ExplicitSchema.Locationremains the cleanest approach for inline instantiations). - Unit Test Isolation: Ensure mock location records used in unit tests follow explicit namespace declarations to prevent unexpected test deployment failures.