Type Conversions in Visual Basic (typecasting)
Converting information from one data type to another is a fairly common programming task. For example, you might retrieve text input for a user that contains the number you want to use for a calculation. Or, you might need to take a calculated value and transform it into text you can display in a web page.
The Visual Basic rules for type conversion are slightly less strict than some other languages, such as C#. For example, VB will automatically allow the (potentially risky) conversions shown here:
Module Module1 Sub Main() Dim BigValue As Integer = 100 Dim SmallValue As Short Dim MyText As String = "100" ' Convert your 32-bit BigValue number into a 16-bit number. SmallValue = BigValue ' Convert your MyText into a number. BigValue = MyText Console.ReadLine() End Sub End Module
The problem with code like this is that it isn’t guaranteed to work correctly at runtime. Conversions are of two types: widening and narrowing. Widening conversions always succeed. For example, you can always convert a number into a string, or a 16-bit integer into a 32-bit integer.
On the other hand, narrowing conversions may or may not succeed, depending on the data. If you’re converting a 32-bit integer to a 16-bit integer, you could encounter a runtime error if the 32-bit number is larger than the maximum value that can be stored in the 16-bit data type. Similarly, some strings can’t be converted to numbers. A failed narrowing conversion will lead to an unexpected runtime error.
It’s possible to tighten up Visual Basic’s type conversion habits by adding an Option Strict instruction to the beginning of your code files.
Option Strict On
In this case, VB will not allow automatic or implicit data type conversions if they could cause an error or lose data. Instead, you’ll need to explicitly indicate that you want to perform a conversion.
To perform an explicit data type conversion in VB, you can use the CType() function. This function takes two arguments. The first specifies the variable you want to convert, and the second specifies the data type you’re converting it to. Here’s how you could rewrite the earlier example with explicit conversions:
Dim BigValue As Integer = 100 Dim SmallValue As Short Dim MyText As String = "100" ' Explicitly convert your 32-bit number into a 16-bit number. SmallValue = CType(BigValue, Short) ' Explicitly convert your string into a number. BigValue = CType(MyText, Integer)