Strings Can Be Nil, Even If They Can't Be Set To Nil

· Mar 23, 02:23 PM

Andy Dent has made available an open-source report-writing engine. Having written some simple report-writing functionality myself, I was interested to see how the professionals do it.

While reading his code, I saw a curious thing.

if aChar is nil or aChar.Len <> 1 then return False

Surely, I thought, he isn’t comparing a string to nil?

Indeed he is, and it appears that as of REALbasic 2008 r4, this is legal. It is, however, undocumented as far as I can tell; I found no mention of it in the release notes nor in the language reference for that version.

Some testing suggests that s is nil returns true if s = “”, and false otherwise. One still cannot assign Nil to a String reference, nor can one compare a String reference to Nil using =.

The ability to compare other String types (CFStringRef, CString, WString, PString) to Nil and to set references of these types was added to REALbasic several releases prior. Thus we can generate pathological results like the following.

dim s as String = ""
dim c as CString = s

Then (s is nil) = true, but (c is nil) = false.

I am not sure whether the ability to compare String references to Nil was an intentional change, or a by-product of some internal fix. Either way, this is a language feature I probably won’t use.

---

Comment

  1. “(c is true) = false.”
    hahaha! ;)

    Thomas Tempelmann · Mar 24, 02:46 AM · #

  2. The fact that this works comes from the fact that internally empty strings can be represented by the string reference pointer being nil.

    However, it is not guaranteed that every empty string is identified this way.

    It may be well possible for a plugin to create a string that with a length of zero, which then is not a simple nil pointer. And then the “s is nil” test will fail, despite the string being empty.

    Someone should tell Andy, probably. Unless someone from RS could tell us that even the plugins won’t be able to do this (unless you’re using Theo’s “faststrings”).

    Thomas Tempelmann · Mar 24, 02:54 AM · #

  3. Unless they’ve changed something since I left, RB’s string foundation code will never return a non-NULL zero-char string object. NULL is the only canonical representation of the empty string.

    Mars Saxman · Mar 25, 08:52 PM · #

Commenting is closed for this article.