Type Conversion Functions

Team-Fly    

 
Visual Basic .NET Unleashed
By Paul Kimmel
Table of Contents
Chapter 2.  Out with the Old, In with the New

Type Conversion Functions

Earlier in the chapter, I recommended that you use Option Strict On and Option Explicit On. These settings will let the compiler help you catch errors at compile-time because they preclude a lot of implicit type conversions. You still need a good way to convert data from one type to another. To this end Visual Basic .NET includes dozens of type conversion capabilities.

Also noted throughout this chapter is the introduction of the ToString method in the Object class. Because every class and structure is an Object, every type contains a ToString conversion method. Many types also contain a method that takes a string argument and converts it to a specific type. For example, in the DateTime type, the Shared Parse method converts a string to a DateTime. The two statements below demonstrate converting a string to a DateTime and a DateTime back to a string, respectively.

 Dim ADate As DateTime = DateTime.Parse("12:00:00 AM") Dim AString As String = ADate.ToString() 

Many of the VB6 conversions have been carried over to VB .NET; a few have been replaced to support new types. In VB6, the conversion functions took an expression of a specific type or variant. In VB .NET the argument type is an Object, which means that you can pass any subclass of an Object that makes sense for the specific kind of conversion. Table 2.9 lists the VB6 conversion functions and their VB .NET replacements .

Table 2.9. VB6 Conversion Functions and Their VB .NET Replacements
VB6 VB .NET Description Range
CBool CBool Converts Object to Boolean Type Valid string or numeric expression
CByte CByte Converts Object To Byte 0 to 255
None CChar Converts Object to Char 0 to 65535
CCur CDec Converts Object to Decimal See VB6's CDec below
CDate CDate Converts Object to DateTime Any valid date or time value
CDbl CDbl Converts Object to Double Any valid Double value (see Table 2.3)
CDec CDec Converts Object to Decimal Any valid Decimal value (see Table 2.3)
CInt CInt Converts Object To Integer Any valid Integer value (see Table 2.3)
CLng CLng Converts Object to Long Any valid Long value (see Table 2.3)
CSng CSng Converts Object to Single Any valid Single value
CStr CStr Converts Object to String Any valid String
CVar CObj Converts Object to Object Any value
None CShort Converts Object to Short Any valid Short (see Table 2.3)

As you can determine from Table 2.9, most conversion functions were carried over to VB .NET. Where the VB6 column contains None, no VB6 conversion function exists.

For reference, see Appendix A, "VB 6 Programming Element Changes in VB .NET."


Team-Fly    
Top
 


Visual BasicR. NET Unleashed
Visual BasicR. NET Unleashed
ISBN: N/A
EAN: N/A
Year: 2001
Pages: 222

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