Visual Basic 2010 (Console) Guide
Conversion
In many of the programs so far, conversion has been taking place implicitly. For example, consider the following few lines of code,
Dim firstNumber As Integer
Console.Write("Enter the first number: ")
firstNumber = Console.ReadLine()
Anything entered in the console is of the string data type. Visual Basic notices the change of data type and tries to adjust accordingly. Providing the input is something that can be converted to an integer, that's what you end up with.
Sometimes it is necessary to perform an explicit conversion. There are a handful of built-in functions that you can use to do this.
Function | Converts To | What You Can Convert |
---|---|---|
CBool() | Boolean | Any valid Char, String or Numeric expression |
CByte() | Byte | 0 - 255 stored as a number - rounded |
CChar() | Char | Any valid string - first character converted |
CDate() | Date | Any valid representation of a date |
CDbl() | Double | Numbers in range |
CDec() | Decimal | Numbers in range |
CInt() | Integer | Numbers in range - rounded |
CLng() | Long | Numbers in range - rounded |
CStr() | String | Pretty much anything |
The expression you want to convert is the parameter for the function. For example,
intValue = CInt(stringExpression)