2.6. Type Conversion


You perform a type conversion when you need to convert or assign values from one type to another. This is also known in some circles as casting. Consider the following code:

 Dim num1 as Short = 25 Dim num2 as Long num2 = num1 

In this case, the VB 2005 compiler will automatically perform an implicit conversion from the Short type to the Long type. Since all the values that could be stored by the Short type can fit into a Long type, this conversion is known as a widening conversion and is a safe operation. The reverse of widening is a narrowing conversion, which is a conversion from a data type that has a larger range to one with a lower range. Consider the following:

 Dim num1 As Long = 25 Dim num2 As Short num2 = num1 

In this example, num1 may potentially contain a value that will cause an overflow in num2 if the assignment takes place. In VB 2005, you can restrict automatic data type conversion by using the Option Strict statement. By default, in VB 2005, the Option Strict statement is set to Off.

VB 6 Tip: In VB 6, there is no Option Strict statement. Hence, the design decision of VB 2005 was to turn Option Strict Off by default so that VB 6 code can be migrated easily.


If you turn Option Strict On, you will need to perform an explicit conversion (or else the compiler will complain):

     '---if option strict on num2 = CShort(num1) '--OR-- num2 = CType(num1, Short) 

You should preferably turn Option Strict On, so that any narrowing operations you are doing are flagged. This will allow you to take action to catch potential errors that might result from a narrowing conversion. Note that in VB 6, performing a narrowing conversion will not set off a warning since the Option Strict statement is not supported.

VB 6 Tip: The familiar type conversion functions like CInt, CStr, and CSng in VB 6 are still supported in VB 2005. In addition, VB 2005 supports the general purpose CType function, which allows you to specify the data type to convert to.


When performing a narrowing conversion, you should always take care to ensure that the operation will not result in a runtime error, such as performing the operation within a try-Catch block. See "Error-Handling," later in this chapter, for more details.



Visual Basic 2005 Jumpstart 2005
Visual Basic 2005 Jumpstart
ISBN: 059610071X
EAN: 2147483647
Year: 2005
Pages: 86
Authors: Wei-Meng Lee

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net