Visual Basic 2008 Programming: Business Applications with a Design Perspective
Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9
Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Appendix A Appendix B Appendix C Home
Loading
Last change: February 13 2016 18:48:19.

 Chapter in PDF

Table of Contents

Chapter 4: Data, Operations, and Built-In Functions
Last change: February 13 2016 18:47:36.
<<PreviousNext>>

The Object Data Type

What if you declare a variable without explicitly giving its type? The variable is then given the Object data type. This is also the data type that VB assumes for you if you use a variable without declaration and you have an Option Explicit Off statement. The Object data type can take on any type of data, numeric or string. In a way, it is a versatile type with a lot of flexibility and capability; however, this versatility can also cause unexpected results and a lot of confusion. Consider the following code:

Dim V As Object V = “1.23” V = V + “45”

What result do you expect? V will contain a string “1.2345” because both V and “45” are strings, and the + symbol is considered a string concatenation operator (see the string section that follows for more explanation). But what do you expect from the following?

V = “1.23” V = V + 45

The answer is 46.23. Because 45 is a number, VB considers + as an addition operator. It thus converts the string “1.23” to the number 1.23 and then performs the addition. After the last statement, V is no longer a string but rather a floating point Double type! In addition to the potentially unexpected result and confusion, the Object type also uses more computer memory to store, and is slower because of the additional complexity involved in handling this data type. Stay away from this data type as much as possible.

Determining the Object Type

When a variable is declared as the object type, you may find a need in your code to determine its data type in order to manipulate the data properly. VB provides two means to handle this: The TypeOf operator and the TypeName function. The TypeOf operator returns the type of the object and has the following syntax:

If TypeOf(Variable) Is Type Then

For example, to determine whether a variable, A, is a string, you can code:

If TypeOf(A) Is String Then . . End If

Notice that this operator can only be used in an If statement and must use Is to check against the type in question.

The TypeName function returns a string that represents the type of of the object. For example, assuming T has been declared as a string variable and A in the preceding code is of the string type, T will contain the value “String” after executing the following code:

T = TypeName(A)

 

Last change: February 13 2016 18:47:37.
<<PreviousNext>>