Run this in Execute Anonymous

system.debug( new SObject[]{}  instanceof SObject );

"compileProblem": "Operation instanceof is always false since an instance of List is never an instance of SObject"

Good to know this. But now try that:

Object o1 = new Integer[]{};
Object o2 = new SObject[]{};
system.debug( o1  instanceof Integer ); // ==> false, as expected
system.debug( o2  instanceof SObject ); // ==> true !!!

That Integer[] is not an instance of Integer sounds reasonable. But why the heck SObject[] is an instance of SObject??

Any ideas what is going on here?

  • 1
    I've raised this internally as a bug (W-10129413). SObject[] should be be an instanceOf SObject when passed via an Object. Nov 4, 2021 at 0:55

1 Answer 1


It's primarily a feature. It allows you to assign a query to a sObject, as in:

Account a = [select Id from account];

Unfortunately, this can introduce bugs. Make sure you check if the variable is a list before checking if a variable is an sObject.

  • 1
    Given how many, um, "special" cases there are in Apex I am surprised they needed instanceof to behave this way to support the assignment. The other thing I have always felt is a very silly effect of such an assignment is an error when the list of SObject instances is empty. Why on earth not just assign null?!
    – Phil W
    Oct 31, 2021 at 9:45
  • 2
    @PhilW I agree. I recall running into this once a long time ago, it's terribly frustrating. And yes, I think they should remove the exceptions. It'd allow millions of lines of code to be cleaned up, rather than the assign-to-list/check-if-not-empty/get-first-value or try/query/catch patterns we've had to endure since 2007.
    – sfdcfox
    Oct 31, 2021 at 11:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .