Conversions

 <  Day Day Up  >  

As discussed earlier in this chapter, every piece of information in a Visual Basic .NET program has a particular type. When you are assigning a value to a variable or performing some operation on two values, all the types involved in the operation must be the same. For example, it is not possible to store a String value into an Integer variable, because the two types are not the same. When you are working with many different types of information, however, it is often necessary to convert one type of information to another. While it is not possible to store a String value into an Integer variable, it is possible to take a String value and convert it into an Integer value (which can then be stored into an Integer variable).

By default, values in Visual Basic .NET will be converted from one type to another as needed. The compiler can do this because the types of all values and variables in Visual Basic .NET are always known and any needed conversions can be deduced from context. In the following example, the value in the String variable is implicitly converted to Integer when a is assigned to b .

 Dim a As String Dim b as Integer a = "10" b = a 

It is also possible to explicitly convert a value from one type to another by using the conversion operators, listed in Table 3-2.

Style

Although they may appear to be functions, the conversion operators are an intrinsic part of the language. Because of that, using the conversion operators is much more efficient than calling the type conversion functions provided by the .NET Framework. The conversion operators should always be used unless there is a compelling reason not to do so.


Table 3-2. Conversion Operators

Operators

Description

CBool(<expr> )

Converts <expr> to Boolean

CByte(<expr>)

Converts <expr> to Byte

CShort(<expr>)

Converts <expr> to Short

CInt(<expr>)

Converts <expr> to Integer

CLng(<expr>)

Converts <expr> to Long

CDec(<expr>)

Converts <expr> to Decimal

CSng(<expr>)

Converts <expr> to Single

CDbl(<expr>)

Converts <expr> to Double

CDate(<expr>)

Converts <expr> to Date

CChar(<expr> )

Converts <expr> to Char

CStr(<expr>)

Converts <expr> to String

CObj(<expr>)

Converts <expr> to Object

CType(<expr>, <type>)

Converts <expr> to <type>

DirectCast(<expr>, <type>)

Converts <expr> to <type> without language-specific conversions

Each conversion operator takes a value of any type and attempts to convert it to the specified type. If the conversion cannot be accomplished, an exception will be thrown at runtime. The conversion operator CType is special in that the destination type is not part of the name of the operator; it is specified as part of the operation.

 Dim a As String Dim b as Integer a = "10" b = CInt(a) b = CType(a, Integer)      Same as the previous statement 

The usefulness of the CType operator will become more apparent later on in the book, when we start dealing with inheritance and interfaces. There is also a special conversion operator, DirectCast , which is useful specifically in inheritance situations. It will also be covered in Chapter 13.

Although the conversion operators are not required to convert from one type to another, using them is generally a good practice, especially when conversions may not succeed. The conversion operators call attention to the fact that a conversion is being performed. Sometimes explicit conversions may also be necessary because the type deduced is not correct. For example:

 Dim a, b As Byte Dim c as Short a = 255 b = 1 c = a + b                 ' Runtime error: overflow c = CShort(a) + CShort(b) ' Succeeds 

In the example, the expression a + b adds two Byte variables together. From this context, the result of the addition is assumed to be a Byte value ”the compiler does not know beforehand that the addition will result in 256 , which is not a valid Byte value. As a result, an error will occur even though the resulting type will fit into the ultimate destination (the variable c , which is typed as Short ). The expression CShort(a) + CShort(b) will succeed, however, because the addition of a Short to a Short is assumed to result in a Short value. Since 256 is a valid Short value, the operation will succeed.

Widening and Narrowing Conversions

Conversions between some types are always guaranteed to succeed, while others are not. In the following example, the first conversion may fail if the Short variable contains a value that will not fit into a Byte variable, whereas the second conversion will always succeed because any value that fits into a Byte variable will fit into a Short variable.

 Dim a As Byte Dim b As Short a = b b = a 

A conversion that is always guaranteed to succeed is called a widening conversion because the set of values that the destination type can hold is wider than the set of values that the source type can hold. In the preceding example, a conversion from Byte to Short is widening because every value of Byte is a valid value of Short as well. A conversion that might fail, however, is called a narrowing conversion because the set of values that the destination type can hold is narrower than the set of values that the source type can hold. Converting a Short value to Byte may or may not succeed, depending on whether the value is in the range of the Byte type.

As discussed in the previous section, explicit conversions between types are not required. However, this can lead programmers into trouble ”it is easy when assigning from one variable to another to forget whether a conversion is being done and whether that conversion is widening or narrowing. If a widening conversion is taking place, there is nothing to worry about ”the conversion is guaranteed to succeed at runtime. But if a narrowing conversion is taking place, the programmer must think about what happens if that conversion should fail. Not handling a conversion failure could cause a serious bug in the application. Therefore, it is always a good idea to do narrowing conversions explicitly by using the appropriate conversion operator.

To assist programmers in remembering to do so, the Option Strict statement can be placed at the beginning of a source file (or set as part of a project's options). One of the things that the Option Strict statement does is require narrowing conversions to be performed explicitly ”if a narrowing conversion is done without a conversion operator, the compiler will give an error.

Style

Because it requires narrowing conversions to be stated explicitly, using Option Strict is highly recommended as good programming practice.


Supported Conversions

Visual Basic .NET supports the following conversions between the fundamental types.

  • Boolean Boolean values can be converted to and from all the numeric types ( Byte , Short , Integer , Long , Decimal , Single , and Double ). When a Boolean value is converted to a signed numeric type (i.e., all types except Byte ), the value True converts into the value “1, and the value False converts into the value 0. For Byte , the value True converts into the value 255. All conversions to and from Boolean are considered narrowing.

    Design

    Although converting Boolean to and from the numeric types is not strictly narrowing, because there is no possibility of failure, the conversion is nonetheless considered narrowing because Boolean is not a numeric type.


  • Byte , Short , Integer , Long , Decimal , Single , and Double ” All the numeric types can be converted to and from one another. There is a progression of conversions that goes in general order of range: Byte , Short , Integer , Long , Decimal , Single , and Double . Any type in the list widens to the types that come after it in the list and narrows to the types that come before it. One thing to note is that while the widening conversions are guaranteed to succeed because the range of every type is contained within all the types later in the list, the precision of values may not be entirely preserved. For example, the following code will print 4.9318203910293E+18.

     Dim a As Long Dim b As Double a = 4931820391029301920 b = a Console.WriteLine(b) 

    Although the Double variable was able to hold the value stored in the Long variable, it wasn't able to store it with the same precision as the Long variable. This is something to keep in mind when you are doing conversions from the integer or fixed-point numeric types to the floating-point types.

    Advanced

    Conversions from floating-point numbers to integer numbers use a method called banker's rounding . In banker's rounding, a floating-point number will be rounded to the nearest integer. If a floating-point number is equally close to the two integers on either side of it, it will be rounded to the closest even number. Thus, 4.5 will round to 4, while 5.5 will round to 6.


  • String String can be converted to and from the Boolean , numeric, and Date types. With the exception of Boolean (which is always converted to and from the English strings "true" and "false," case insensitively), all the conversions are done using the current UI culture of the .NET Framework. That is, while the value 10.5 will convert to the string "10.5" on a machine with a US English culture setting, it will convert to the string "10,5" on a machine with a French culture setting, and vice versa. This is because in the US English culture the period is used as the decimal point, while the comma is used as the decimal point in the French culture (and many others). Also, when converting from String , currency values (also tied to the current culture setting) will be recognized and converted ”so the string "$10.50" will convert to the Double value 10.5 if US English is the current culture.

Advanced

The current culture being used for conversions on a particular thread can be read or changed through the System.Thread.CurrentCulture and System.Thread.CurrentUICulture properties.


 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

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