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
expression
is 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
expression
can be any data, object, structure, or interface type.typename
can be any data type (such asBoolean
,Byte
,Decimal
,Long
,Short
,String
, etc.), structure type, object type, or interface that can be used with theAs
clause in aDim
statement.If the function fails, or if the converted value of
expression
is outside the range allowed bytypename
, an InvalidCastException exception occurs.When
Option
Strict
is 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, ifOption
Strict
isOn
, 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 ...
Get VB.NET Language in a Nutshell, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.