O'Reilly logo

VB.NET Language in a Nutshell, Second Edition by Steven Roman PhD, Paul Lomax, Ron Petrusha

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 as Boolean, Byte, Decimal, Long, Short, String, etc.), structure type, object type, or interface that can be used with the As clause in a Dim statement.

  • If the function fails, or if the converted value of expression is outside the range allowed by typename, 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 use CType. For instance, if Option Strict is On, 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required