Instanceof null is true in Apex

PS From the API version of Winter ’15 onwards, the more rational value of false will be returned.

Here is a Java test case that demonstrates some of the behavior of instanceof including that instanceof evaluates to false for null values:

public class InstanceofTest extends TestCase {
    public void testNull() {
        Date d = null;
        doTest(d, false);
        doTest(null, false);
    public void testNotNull() {
        doTest(new Date(), true);
        doTest("foo", false);
    private void doTest(Object o, boolean expected) {
        assertEquals(expected, o instanceof Date);

Surprisingly in Apex instanceof evaluates to true for null values:

private class InstanceofTest {
    static void testNull() {
        Date d = null;
        doTest(d, true);
        doTest(null, true);
    static void testNotNull() {
        doTest(Date.newInstance(2010, 1, 1), true);
        doTest('foo', false);
    private static void doTest(Object o, Boolean expected) {
        System.assertEquals(expected, o instanceof Date);

So if you are using instanceof in Apex, think about adding null guards to avoid unexpected results.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s