Implicit and Explicit Conversions

An implicit conversion does not require any special syntax in the source code. In the following example, Visual Basic .NET implicitly converts the value of K to single-precision floating point before assigning it to Q.

An explicit conversion uses a type conversion keyword. Visual Basic .NET provides several such keywords, which coerce an expression in parentheses to the desired data type. These keywords act like functions, but the compiler generates the code inline, so execution is slightly faster than with a function call.

In the following extension of the preceding example, the CInt keyword converts the value of Q back to an integer before it is assigned to K:

When converting to an elementary type (including an array of an elementary type), the same types as allowed for the corresponding conversion keyword

When converting to a composite type, the interfaces it implements and the classes from which it inherits

The CType Keyword

The CType keyword operates on two arguments. The first is the expression to be converted, and the second is the destination data type or object class. The following example demonstrates the use of CType.

You can use CType to convert values to composite data types as well as to elementary types. You can also use it to coerce an object class to the type of one of its interfaces, as in the following example:

Dim V() As ClassV ' Array of ClassV objects.
Dim ObArray() As Object ' Array of objects to be assigned.
' Some object array is assigned to ObArray.
If TypeOf ObArray Is ClassV() ' Check for run-time type compatibility.
V = CType(ObArray, ClassV()) ' ObArray can be converted to ClassV.
End If

Note Values used with a conversion keyword must be valid for the destination data type, or an error occurs. For example, if you attempt to convert a Long to an Integer, the value of the Long must be within the valid range for the Integer data type.

Caution Specifying CType to convert from one class type to another fails at run time if there is no inheritance relationship between the two types.

Performing an explicit conversion is also known as casting an expression to a given data type or object class.