Name
CType Function
Named Arguments
No
Syntax
CType(expression,typename)
-
expression(required; any) The data item to be converted
-
typename(required; Keyword) The data type, object type, structure, or interface to which
expressionis to be converted
Return Value
expression cast as a
typename interface, object, structure, or
data type
Description
Converts an expression to the specified data type if possible; otherwise, returns an error.
Rules at a Glance
expressioncan be any data, object, structure, or interface type.typenamecan be any data type (such asBoolean,Byte,Decimal,Long,Short,String, etc.), structure type, object type, or interface that can be used with theAsclause in aDimstatement.If the function fails, or if the converted value of
expressionis outside the range allowed bytypename, an InvalidCastException exception occurs.When
OptionStrictis set to On, then implicit data type conversions can only be widening; that is, implicit data type conversion only occurs from smaller data types to “wider” data types, such as from Integer to Long. In this case, to perform a narrowing type conversion, we can useCType. For instance, ifOptionStrictisOn, the following code produces an error:Dim iInteger As Integer = 1 Dim lLong As Long = 2 iInteger = lLong On the other hand, the following code is fine: Dim iInteger As Integer = 1 Dim lLong As Long = 2 iInteger = Ctype(lLong, Integer)
Example
Option Strict On Imports Microsoft.VisualBasic Imports System Interface IEmployee ...