Beware of Boolean coercion weirdness

The final issue with Debug.Assert is Boolean type coercion. Later in this chapter, we’ll look at Visual Basic’s automatic type coercion rules and where they can lay nasty traps for you. For now, you can be content with studying the following little enigma:

Dim nTest As Integer
nTest = 50
Debug.Assert nTest
Debug.Assert Not nTest

You will find that neither of these assertions fire! Strange, but true. The reason has to do with Visual Basic coercing the integer to a Boolean. The first assertion says that nTest = 50, which, because nTest is nonzero, is evaluated to TRUE. The second assertion calculates Not nTest to be -51, which is also nonzero and again evaluated to TRUE.

However, if you compare nTest and Not nTest to the actual value of TRUE (which is -1) as in the following code, only the first assertion fires:

Debug.Assert nTest = True
Debug.Assert Not nTest = True

Some Final Thoughts Debug.Assert is a very powerful tool for bug detection. Used properly, it can catch many bugs automatically, without any human intervention. (See the discussion of an Assertion Sourcerer on page 314 for a utility that supplements Debug.Assert.)