Visual Basic

Using Variants Instead of Objects

Earlier in the chapter, I extolled the use of Variants in the place of simple data types like Integer and String. Does the same argument apply for objects?

Put simply, the answer is no, because there is considerable extra value added by declaring a variable to be of a specific object type. Unlike the simple data types, we can get useful compile-time error messages that help prevent bugs. If the Variant (or Object) data type was used, these errors would surface only at run time-a bad thing.

By way of explanation, consider the following simple example. In this project there is one class, called Cow, which has few properties, such as Age, TailLength, and so forth. We then create a routine

Private Sub AgeMessage(c As Cow)
      MsgBox c.Age
  End Sub

If you accidentally misspell Age and instead type

MsgBox c.Agg

provided c is declared as Cow, you will receive a compile-time error message so that you can correct it. If the parameter was declared as a Variant (or Object), Visual Basic cannot know whether there is a legitimate property of c called Agg until, at run time, it actually knows what the object is. Hence, all you get is a run-time error 438 instead.

Notice how this argument does not apply back to simple data types. Although simple data types do not have properties, they do have certain operators that may or may not be well defined for them. However, a piece of code such as this

Dim s As String
  s = s * s

where the * operator is undefined for strings, will result in a run-time type mismatch, not a compile-time error. So the advantage of not declaring as Variant is lost.

Other Variant Subtypes

Flexibility is the fundamental reason to use Variants. But the built-in flexibility of Variants is not advertised enough, and consequently they tend to be underused. The use of Empty, Null, and Variant arrays-and now in version 6, UDTs-remain underused in the Visual Basic programmer community.