Data Type Conversion


Normally, you assign a value to a variable that has the same data type as the value. For example, you assign a string value to a String variable, you assign an integer value to an Integer variable, and so forth. Whether you can assign a value of one type to a variable of another type depends on whether the conversion is a narrowing or widening conversion.

Narrowing Conversions

A narrowing conversion is one where data is converted from one type to another type that cannot hold all of the possible values allowed by the original data type. For example, the following code copies the value from a Long variable into an Integer variable. A Long value can hold values that are too big to fit in an Integer, so this is a narrowing conversion. The value contained in the Long variable may or may not fit in the Integer.

  Dim an_integer As Integer Dim a_long As Long ... an_integer = a_long 

The following code shows a less obvious example. Here the code assigns the value in a String variable to an Integer variable. If the string happens to contain a number (for example “10” or “1.23”), the assignment works. If the string contains a non-numeric value (such as “Hello”), however, the assignment fails with an error.

  Dim an_integer As Integer Dim a_string As String ... an_integer = a_string 

Another non-obvious narrowing conversion is from a class to a derived class. Suppose that the Employee class inherits from the Person class. Then setting an Employee variable equal to a Person object, as shown in the following code, is a narrowing conversion because you cannot know without additional information whether the Person is a valid Employee. All Employees are Persons, but not all Persons are Employees.

  Dim an_employee As Employee Dim a_person As Person ... an_employee = a_person 

If you have Option Strict turned on, Visual Basic will not allow implicit narrowing conversions. If Option Strict is off, Visual Basic will attempt an implicit narrowing conversion and throw an error if the conversion fails (for example, if you try to copy the Integer value 900 into a Byte variable).

To make a narrowing conversion with Option Strict turned on, you must explicitly use a data type conversion function. Visual Basic will attempt the conversion and throw an error if it fails. The CByte function converts a numeric value into a Byte value, so you could use the following code to copy an Integer value into a Byte variable:

  Dim an_integer As Integer Dim a_byte As Byte ... a_byte = CByte(an_integer) 

If the Integer variable contains a value less than 0 or greater than 255, the value will not fit in a Byte variable so CByte throws an error.

The following table lists the data type conversion functions of Visual Basic.

Open table as spreadsheet

Function

Converts To

CBool

Boolean

CByte

Byte

CChar

Char

CDate

Date

CDbl

Double

CDec

Decimal

CInt

Integer

CLng

Long

CObj

Object

CSByte

SByte

CShort

Short

CSng

Single

CStr

String

CUInt

UInteger

CULng

ULong

CUShort

UShort

The CInt and CLng functions round fractional values off to the nearest whole number. If the fractional part of a number is exactly .5, the functions round to the nearest even whole number. For example, 0.5 rounds to 0, 0.6 rounds to 1, and 1.5 rounds to 2.

In contrast, the Fix and Int functions truncate fractional values. Fix truncates toward zero, so Fix(-0.9) is 0 and Fix(0.9) is 0. Int truncates downward, so Int(-0.9) is -1 and Int(0.9) is 0.

Fix and Int also differ from CInt and CLng because they return the same data type they are passed. CInt always returns an Integer no matter what type of value you pass it. If you pass a Long into Fix, Fix returns a Long. In fact, if you pass a Double into Fix, Fix returns a Double.

The CType function takes as parameters a value and a data type, and it converts the value into that type if possible. For example, the following code uses CType to perform a narrowing conversion from a Long to an Integer. Because the value of a_long can fit within an integer, the conversion succeeds.

  Dim an_integer As Integer Dim a_long As Long = 100 an_integer = Ctype(a_long, Integer) 

The DirectCast statement changes value types much as CType does, except that it only works when the variable it is converting implements or inherits from the new type. For example, suppose that the variable dessert_obj has the generic type Object and you know that it points to an object of type Dessert. Then the following code converts the generic Object into the specific Dessert type.

  Dim dessert_obj As Object = New Dessert("Ice Cream") Dim my_dessert As Dessert my_dessert = DirectCast(dessert_obj, Dessert) 

DirectCast throws an error if you try to use it to change the object’s data type. For example, the following code doesn’t work, even though converting an Integer into a Long is a narrowing conversion.

  Dim an_integer As Integer = 100 Dim a_long As Long a_long = DirectCast(an_integer, Long) 

The TryCast statement converts data types much as DirectCast does, except that it returns Nothing if there is an error, rather than throwing an error.

Data Type Parsing Methods

Each of the fundamental data types except for String has a Parse method that attempts to convert a string into the variable type. For example, the following two statements both try to convert the string value txt_entered into an Integer:

  Dim txt_entered As String = "112358" Dim num_entered As Integer ... num_entered = CInt(txt_entered)             ' Use CInt. num_entered = Integer.Parse(txt_entered)    ' Use Integer.Parse. 

Some of these parsing methods can take additional parameters to control the conversion. For example, the numeric methods can take a parameter that gives the international number style the string should have.

The class parsing methods have a more object-oriented feel than the conversion functions. They are also a bit faster. They only parse strings, however, so if you want to convert from a Long to an Integer, you need to use CInt rather than Integer.Parse.

Widening Conversions

In contrast to a narrowing conversion, a widening conversion is one where the new data type is always big enough to hold the old data type’s values. For example, a Long is big enough to hold any Integer value, so copying an Integer value into a Long variable is a widening conversion.

Visual Basic allows widening conversions. Note that some widening conversions can still result in a loss of data. For example, a Decimal variable can store more significant digits than a Single variable can. A Single can hold any value that a Decimal can but not with the same precision. If you assign a Decimal value to a Single variable, you may lose some precision.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net