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.
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)
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. |