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”), the assignment works. If the string contains a non-numeric value (such as “Hello”), 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 generate an error at run time if the conversion fails.

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 generate an error if it fails. For example, 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.

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 0.5, the functions round to the nearest even whole number. For example, 0.5 rounds down to 0, 0.6 rounds up to 1, and 1.5 rounds up 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 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 you can always store an integer value in a Long variable:

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 two final statements in the following code 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 or Int32.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, so if you assign a Decimal value to a Single variable, you may lose some precision.

The Convert Class

The Convert class provides an assortment of methods for converting a value from one data type to another. For example, the following code uses the ToInt32 method to convert the string “17” into a 32-bit integer:

Dim i As Integer = Convert.ToInt32("17")

These methods are easy to understand so they make code simple to read. Unfortunately they work with particular data type sizes such as 16- or 32-bit integer rather than with the system’s default integer size so they may require you to change your code in the future. For example, if a later version of Visual Basic assumes 64-bit integers, then you may need to update your calls to Convert methods.

ToString

The ToString method is a conversion function that is so useful it deserves special mention. Every object has a ToString method that returns a string representation of the object. For example, the following code converts the integer value num_employees into a string:

Dim txt As String = num_employees.ToString()

Exactly what value ToString returns depends on the object. For example, a double’s ToString method returns the double formatted as a string. More complicated objects tend to return their class names rather than their values (although you can change that behavior by overriding their ToString methods).

ToString can take as a parameter a format string to change the way it formats its result. For example, the following code displays the value of the double angle with two digits after the decimal point:

MessageBox.Show(angle.ToString("0.00"))

Appendix P, “Date and Time Format Specifiers,” and Appendix Q, “Other Format Specifiers,” describe format specifiers in greater detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.178.190