Example 1: Assignment between incompatible variables

Consider the following code fragment:

Dim i As Integer, s As String
s = "Hello"
i = s

What happens? Well, it depends on which version of Visual Basic you run. In Visual Basic 3, you get a Type mismatch error at compile time. In Visual Basic 5, there are no errors at compile time, but you get the dialog box shown in Figure 5-2 when the program encounters the i = s line of code.

Figure 5-2 The dialog box that appears when i = s is encountered

The difference is that the error occurs at run time instead of being trapped when you compile. Instead of you finding the error, your users do. This is a bad thing.

The situation is further complicated because it is not the fact that s is a string and i is an integer that causes the problem. It is the actual value of s that determines whether the assignment can take place.

This code succeeds, with i set to 1234:

Dim i As Integer, s As String
s = "1234"
i = s

This does not (you might have thought that i would be set to 0):

Dim i As Integer, s As String
s = ""
i = s

These two examples demonstrate why you get the error only at run time. At compile time, the compiler cannot know what the value of s will be.

The behavior is exactly the same with this piece of code:

Dim i As Integer, s As String
s = ""
i = CInt(s)

In other words, a hidden call to the CInt () function takes place. The rules that determine whether CInt () will succeed are the same as the rules that determine whether the plain i = s will succeed. This is known as implicit type conversion, although some call it “evil” type coercion.

If you don’t use Variants, you should use some form of Hungarian notation to help you identify possible mismatches.

This code, on the other hand, succeeds in all versions of Visual Basic:

Dim i As Variant, s As Variant
s = "Hello"
i = s

Do you think I’m sidestepping the issue? I don’t. Using Variants all but eliminates run-time type mismatch errors. The important point is that you have to go into it wholeheartedly. If you use only some Variants, you’ll find you get even more type problems. Use all Variants, and you will get the reward.