Skip to Content
VB.NET Language in a Nutshell, Second Edition
book

VB.NET Language in a Nutshell, Second Edition

by Steven Roman PhD, Ron Petrusha, Paul Lomax
April 2002
Intermediate to advanced
688 pages
19h 51m
English
O'Reilly Media, Inc.
Content preview from VB.NET Language in a Nutshell, Second Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

VB .NET Language in a Nutshell

VB .NET Language in a Nutshell

Steven Roman PhD, Ron Petrusha, Paul Lomax

Publisher Resources

ISBN: 0596003080Supplemental ContentCatalog PageErrata