Data Type Changes

In the move to .NET, Visual Basic's data types were adjusted in a couple of ways. I will go into more detail on integers and variants, but here is a quick summary of the changes:

  • The Currency data type has been removed completely, but you can use the Decimal data type instead.

  • Date values in Visual Basic 6.0 were stored as Doubles, and programmers often manipulated them as such, but in Visual Basic .NET DateTime values are stored as 64-bit integers instead. If you need to convert a .NET DateTime value into or from a Double, you can use the System.DateTime.ToOADate or FromOADate methods.

  • Integers were 16-bit values in VB6, they are now 32-bit. Longs have also moved from 32-bit to 64-bit, and a new data type (Short) has been added to Visual Basic to handle 16-bit numbers.

  • Variants were special data types in VB6 that could hold anything from Integer or String values to object references. They no longer exist in Visual Basic .NET, but the Object data type is available and is, like a Variant, capable of holding any data type.

  • The Framework provides a set of type-conversion functions, but the standard Visual Basic type-conversion functions are still available.

Integers

Visual Basic has its roots as a 16-bit development language, not moving up into the 32-bit world until version 4.0, and that heritage resulted in a set of data types in Visual Basic 6.0 that did not line up well with other languages or the underlying operating system. As part of the move to .NET, Visual Basic's integer data types were redefined to make it easier for interoperability with other .NET languages. The following table shows various sizes of signed integers that are commonly used and the equivalent data type across Visual Basic 6.0, Visual Basic .NET, C#, and the underlying framework data type that corresponds to the language specific names.

INTEGER SIZE (SIGNED)VISUAL BASIC 6.0VISUAL BASIC .NETC#FRAMEWORK
16-bit (word)IntegerShortshortSystem.Int16
32-bit (dword)LongIntegerintSystem.Int32
64-bit (qword)(none)LonglongSystem.Int64

As you can see, the Framework equivalents are named to avoid any confusion about their size, and for that fact alone, it might be worth considering using them. Personally, I use the Visual Basic data types, (such as Integer and Long), and I think the habit is too strong to break easily. Either way, it makes no difference to the compiler; the Visual Basic and C# data types are actually just aliases to the Framework types, so that you can continue to work using the terms you are comfortable with depending on your programming background.

Variants and Objects

There are two main types of variables, value types and reference types. Reference types represent data types where the variable holds a pointer to the actual object, compared to a value type where the variable holds the actual data for the type in question. Integers, Doubles, and Bytes are all examples of value types, whereas Forms, Classes, and Strings are examples of reference types. In Visual Basic 6.0, any variable could be stored into a Variant, regardless of whether it was a reference or a value type, and the same is true with .NET's Object data type.

This is a little confusing because the Object data type is a reference type, it holds pointers to values, but yet it can be used to store both reference and value types. It would be an over-simplification to state, “Everything in .NET is an Object,” but it certainly seems that way. In truth, what occurs is that value types are “boxed” or wrapped in a special reference type so that they can be stored in an Object variable. When you take these values out of an Object variable and back into a value type (an Integer, for example), the object is “unboxed” to extract only the actual value instead of a reference. This boxing/unboxing process means that using Object variables to store all of your values, instead of explicitly typing them (into Integers, Doubles, and so on), is inefficient and should be avoided.

Converting Between Data Types

Visual Basic 6.0 includes support for converting from one data type to another, but with the addition of Option Strict, (if you choose to use it) you will need to explicitly convert from one data type to another more frequently. There are many ways to handle conversion in Visual Basic .NET, and it all depends on what you are doing, so I will first discuss the two types of data type conversion that occur.

  • Parsing (actually interpreting the data and coming up with the equivalent in another data type)

  • Type coercion (or casting, as it is commonly known in the C++/C# world)

Both types of conversion are often mistaken as exactly the same thing, and that confusion makes it difficult to pick the correct style of conversion. The following sections explain both of the types individually, with examples, to illustrate the difference.

Parsing

Say you have an application where the user can enter a number into one textbox and a date into another. Now, in your code you do not want to work with the two strings that are available through the .Text property of these textboxes, you want to work with an Integer and a Date variable. This is a classic example where parsing is required; a string is not a date or an integer, it is a collection of character codes, and the underlying numeric value of those codes isn't at all related to the date or numeric value the user typed. To take a text value like $12,500.00 and convert it to an integer, or to convert a string containing "October 5, 2003" into a date requires parsing. In VB .NET, there are three ways to parse a value into a different data type; using the Parse methods on the data type itself, using the methods of a Framework class called Convert, or using the built-in VB .NET functions. In the first case, you are taking advantage of the special function (Parse) available on each of the basic data types, as shown in Listing 2.6.

Listing 2.6. Using the Parse Method on a Data Type
Private Sub btnParse_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
            Handles btnParse.Click
    Dim myDate As Date
    Dim myInteger As Integer

    myDate = Date.Parse(Me.dateEntry.Text)
    myInteger = Integer.Parse(Me.numberEntry.Text)

    MsgBox(myDate)
    MsgBox(myInteger)
End Sub
						

For the second method, you are using the methods of a class within the Framework called System.Convert. This class provides methods for conversion to all of the standard types (ToInt32, ToInt64, ToString, ToDateTime, and so on) and a few less standard ones as well. You can pass any type of data into one of these conversion functions and it will attempt to parse it into the desired data type. Under the covers, Convert.To eventually calls the same Parse method I described in the first section, so the actual handling of strings is the same. The code in Listing 2.7 illustrates the same functionality as the previous listing, but using the System.Convert methods.

Listing 2.7. Using System.Convert
Private Sub btnConvert_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
            Handles btnConvert.Click
    Dim myDate As Date
    Dim myInteger As Integer

    myDate = System.Convert.ToDateTime(Me.dateEntry.Text)
    myInteger = System.Convert.ToInt32(Me.numberEntry.Text)

    MsgBox(myDate)
    MsgBox(myInteger)
End Sub

In Listing 2.8, you are using a more generalized solution. The Visual Basic .NET conversion functions (CDate, CInt, CDec, and so on) will convert values in any one of several ways, one of which is through parsing.

Listing 2.8. Using the Visual Basic Conversion Functions
Private Sub btnVBConvert_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
            Handles btnVBConvert.Click
    Dim myDate As Date
    Dim myInteger As Integer

    myDate = CDate(Me.dateEntry.Text)
    myInteger = CInt(Me.numberEntry.Text)

    MsgBox(myDate)
    MsgBox(myInteger)
End Sub

It is important to realize that these Visual Basic specific conversion functions are more powerful than the basic Parse and Convert.To methods described previously. For example, look at how each of these routines handles converting a selection of sample strings into integers.

StringInteger.ParseConvert.ToInt32CInt
"12,500"ErrorError12500
"12"121212
"12500"125001250012500
"12500.00"ErrorError12500
"$12,500.00"ErrorError12500
"$12,500.10"ErrorError12500
"&HFF" (VB syntax for the hex value FF) 255ErrorError

As the table clearly indicates, CInt is capable of successfully parsing a much wider range of acceptable text values into integers. You will obtain similar results if you compare the corresponding functions for other data types. Another standard Visual Basic function available in Visual Basic .NET, IsNumeric, correctly recognizes the same strings as CInt() as being numeric values. If you need to convert into a type other than the ones covered by CInt, CStr, and the other pre-existing conversion methods, you can use CType. CType takes two arguments, the variable or value to be converted and the desired type. The following line of code shows how you can use CType to convert a variable into an uncommon type.

Dim myClass As Class1 = CType(myObj, Class1)

Type Coercion (Casting)

Both of these methods are performing conversions, but I consider a true data type conversion to be when you view the information in the variable as another data type. It is the same data, different view. As an example, consider this routine that accepts one of its parameters into a variable typed as an object. The Object type is essentially the same as stating no type information at all, so before you can use the value passed into this routine you will likely want to convert it into a strongly typed variable such as an integer (see Listing 2.9).

Listing 2.9. Sometimes You Have an Object When You Want a Strongly Typed Variable Such as an Integer
Sub ShowMyName(ByVal numberOfTimes As Object)

End Sub

Now, if the variable passed in was actually an integer, you are really just casting it back to that data type; you are not converting/changing it. To perform a conversion of this type in Visual Basic .NET you could use the CInt, CDate, CDouble, and so on functions, but you can also perform a true cast (just changing the data type of the value without interpreting or changing the information) by using the DirectCast function.

DirectCast is new to VB .NET, and it is a more efficient way to coerce a variable from one type to another, but it will work only if the object you are trying to cast is truly of the destination type. In general, the CInt, CDec, and CDbl functions are more flexible and will work in a wider range of situations. In many situations where I would consider using DirectCast, I first check the value to ensure that it truly is of the correct type for a DirectCast to succeed. To check a value's type, you can use the TypeOf keyword, as shown on line 2 of Listing 2.10.

Listing 2.10. If You Know the Underlying Type of a Variable You Can Use DirectCast to Coerce it from Object to a Strongly Typed Value
Sub ShowMyName(ByVal numberOfTimes As Object)
    If TypeOf numberOfTimes Is Integer Then
        Dim idx, repeatCount As Integer
        repeatCount = _
            DirectCast(numberOfTimes, Integer)
        For idx = 1 To repeatCount
            Debug.WriteLine("Duncanma")
        Next
     End If
End Sub
						

No More “Set” or “Let”

Visual Basic 6.0 treats assigning an object type to a variable differently than assigning a value type; objects require the use of a special Set keyword, whereas value types can either use the Let keyword or just omit the keyword altogether. Listing 2.11 illustrates the different syntax required for value types and object types.

Listing 2.11. In Visual Basic 6.0, You Had to Use the Set keyword to Assign an Object Reference to a Variable
Private Sub Command1_Click()
    Dim thisCurrentForm As Form
    Set thisCurrentForm = Me

    Dim myInteger As Integer
    myInteger = 3
    Let myInteger = 3 'same as previous line
End Sub

Visual Basic .NET makes no distinction between the two types of assignment (as shown in Listing 2.12); both are accomplished with the equals sign and no special keyword.

Listing 2.12. No More Set or Let in Your Visual Basic .NET Code!
Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
            Handles Button1.Click
    Dim thisCurrentForm As Form
    thisCurrentForm = Me

    Dim myInteger As Integer
    myInteger = 3
End Sub
					

No More “As Any”

When creating declarations for external procedures (such as Win32 APIs) in Visual Basic 6.0, it was possible to declare a parameter As Any (see Listing 2.13). This indicates that multiple data type values were possible and you could pass in any one of them to the API call.

Listing 2.13. In Visual Basic 6.0, As Any Allowed You to Declare an API Call Without Specifying a Specific Data Type
Public Declare Function SendMessage _
    Lib "user32" Alias "SendMessageA" _
    (ByVal hwnd As Long, ByVal wMsg As Long, _
     ByVal wParam As Long, lParam As Any) As Long

In Visual Basic .NET, you must be more specific; if a parameter of an API call can take more than one data type, you can declare more than one variation on the call and pick which one you want to use based on the data type. Declaring more than one version of a specific external procedure is possible due to the new OO features in Visual Basic .NET (specifically a concept called overloading), which is discussed in Chapter 7, “Object Oriented Programming in Visual Basic .NET.”

Listing 2.14. By Using Overloads in Visual Basic .NET, You Can Use Strongly Typed Values, While Still Supporting More than One Data Type
Public Overloads Declare Function SendMessage _
    Lib "user32" Alias "SendMessageA" _
    (ByVal hwnd As Long, ByVal wMsg As Long, _
     ByVal wParam As Long, ByVal lParam As Integer) As Long

Public Overloads Declare Function SendMessage _
    Lib "user32" Alias "SendMessageA" _
    (ByVal hwnd As Long, ByVal wMsg As Long, _
     ByVal wParam As Long, ByVal lParam As String) As Long

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

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