The data type used most in earlier versions of the language up to VB 6 was the Variant (which was replaced in subsequent versions by the Object type). A variable declared as Object can store anything, and any variable that hasn’t been declared explicitly is an Object variable. Even if you turn on the Strict option, which forces you to declare the type of each variable (and you should always have this option on), you will eventually run into Object variables. When you retrieve an item from a ListBox control, for example, you get back an object, not a specific data type. In the previous chapter, we used the ListBox control to store Contact objects. Every time we retrieved a contact from the control’s Items collection, however, we got back an Object variable. To use this object in our code, we had to convert it to a more specific type, the Contact type, with the CType() or DirectCast functions. The same is true for an ArrayList, which stores objects, and we usually cast its members to specific types.
Variables declared without a specific type are called untyped variables. Untyped variables should be avoided — and here’s why. The following expression represents a ListBox item, which is an object:
Code language: CSS (css)
Even if you add a Customer or a Product object to the list, when you retrieve the same item, it’s returned as a generic Object variable. If you type the preceding expression followed by a period, you will see in the IntelliSense drop-down list the members of the generic Object variable, which you hardly ever need. If you cast this item to a specific type, the IntelliSense box will show the members of the appropriate type.
The action of changing a variable’s type is known as casting, and there are two methods for casting variable types — the old VB 6 CType() function and the new DirectCast() function:
Code language: PHP (php)
Dim currentCustomer As Customer currentCustomer = CType(ListBox1.Items(3), Customer)
From now on, you can access the members of the currentCustomer object as usual.
The TryCast() Function
If the specified type conversion can’t be carried out, the CType() function will throw an InvalidCastException exception. As a reminder, a variation of the CType() and DirectCast() functions is the TryCast() function, which attempts to convert a variable into another type. If the conversion is not possible, the TryCast() function doesn’t throw an exception, but returns the Nothing value. Here’s how the TryCast() function is used:
Code language: PHP (php)
Dim o As Object o = New Customer("Jack Sparrow", "BLACK PEARL") c = TryCast(o, Contact) If c Is Nothing Then MsgBox("Can't convert " & o.GetType.Name & " to Contact") Exit Sub End If ' statements to process the c object variable