4

Is it possible to create a method that will return any sObject type?

Why?

I want to create a method that combines DML operations, but the initial method that is called should be able to return any sObject type.

7

You can always create a method to return a SObject. Something as below:

public SObject mySObject() {
    if(condition) {
        return new Account();
    } else {
        return new Contact();
    }
}

It will though depend on how you want to utilize it from your calling context. You can always get the SObjectType in your calling context and take actions accordingly. E.g.,

SObject s = mySobject();
system.debug(s.getSObjectType());
// execute other code based on type
  • even better is to return a List<SObject> so caller can work with collection idioms – cropredy Apr 24 at 17:56
  • @cropredy Agreed. This was more of a direct answer to the question itself, definitely always scope of improvements/refinement based on actual requirements. – Jayant Das Apr 24 at 17:57
  • You can also use instanceof (e.g. if(s instanceof Account)) or a switch statement – IllusiveBrian Apr 24 at 19:36
  • @IllusiveBrian That's true. Many different ways of doing that. This was mostly a sample/approach, which is always open for refinement in actual implementation. – Jayant Das Apr 25 at 17:48

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.