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:

@isTest
private class InstanceofTest {
    @isTest
    static void testNull() {
        Date d = null;
        doTest(d, true);
        doTest(null, true);
    }
    @isTest
    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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s