Home -> Programming -> Processing -> Type Conversions

Type Conversions

One of the consequences of creating different data types for our variables is that when we want to assign data to a variable which has a different data type, it must be converted to the other data type. Actually VB will do these conversions for us, but if something goes wrong the result is reported to us as an exception error. For beginning programmers, trying to read and understand error messages is like trying to learn Egyptian hieroglyphics. To make this easier I have recommended on an earlier page in this site that you set Option Strict to On. This setting causes type checking to be done in the editor and possible type conversion errors are reported as syntax errors rather than exception errors. Syntax errors are always easier to find and fix than exception errors. Conversions from one data type to another can be done in two ways.

The first way is an older standard and the conversion is a function call. To convert numerical data to string for example:

    CStr(argument)

where argument is the literal, variable or property being converted.

Common conversions which convert from a string to a number are:

    CSng(argument) converts string data or non-single numeric data to single.

    CDbl(argument) converts string data or non-double numeric data to double.

    CInt(argument) converts string data or non-integer numeric data to integer.

    CDate(argument) converts appropriate data (usually string) into date data type.

The second way to convert data uses the newer object-oriented design of VB and calls the conversion method of the given class to convert the data to the desired data type. For example to convert a number in a variable called Total to a string so we can display it in a label would look like this:

    lblOutput.Text = Total.ToString

Notice here the conversion call is tacked onto the end of Total which would be a numeric variable. Microsoft is encouraging people to use the newer object-oriented forms of type conversions. However, depending on the particular coding situation, the older forms are sometimes more convenient to use. Other conversions using object methods are:

    .ToInt converts data type to integer.