Explicit Conversion Functions

Visual Basic 2008 provides a number of conversion functions in addition to CByte() that enable you to explicitly allow a narrowing cast when Option Strict is enabled. Table 3-7 documents the core VB 2008 conversion functions.

Table 3-7. VB 2008 Conversion Functions

Conversion Function

Meaning in Life

CBool

Copies a Boolean expression (such as the number 0) into a Boolean value

CByte

Copies an expression into a Byte

CChar

Copies the first character of a string into a Char

CDate

Copies a string containing a data expression into a Date

CDbl

Copies a numeric expression double precision

CDec

Copies a numeric expression of the Decimal type

CInt

Copies a numeric expression into an Integer by rounding

CLng

Copies a numeric expression into a long integer by rounding

CObj

Copies any item into an Object

CSByte

Copies a numeric expression into an SByte by rounding

CShort

Copies a numeric expression into a Short by rounding

CSng

Copies a numeric expression into a Single

CStr

Returns a new string representation of the expression

CUInt

Copies a numeric expression into a Ulnteger by rounding

CULng

Copies a numeric expression into a ULong by rounding

CUShort

Copies a numeric expression into a UShort by rounding

Visual Basic 2008 also supports the CType function. CType takes two arguments, the first is the "thing you have," while the second is the "thing you want." For example, the following conversions are functionally equivalent:

Sub Main()

Dim myByte As Byte Dim myInt As Integer = 200 myByte = CByte(myInt) myByte = CType(myInt, Byte)

Console.WriteLine("Value of myByte: {0}", myByte) End Sub

One benefit of the CType function is that it handles all the conversions of the (primarily VB6-centric) conversion functions shown in Table 3-7. Furthermore, as you will see later in this text,

CType allows you to convert between base and derived classes, as well as objects and their implemented interfaces.

Was this article helpful?

0 0

Post a comment