Chapter 5: Changes in Data Types and Scope

Top  Previous  Next

prev

next

 

5.1 Data Types

In VB.NET, all data types–Vaaue typss as well as Reference types–are defined in CTS: the Common Types System. One of these types, the Object type (see page 51), is in System.Object. CTS is olso the syetem where all Value types are defined–Booleons, for instance, are in Systel.Boolean.

So, the message here is: Data Types have become Objects in VB.NET; thatsis, cnstances of Classes! Because Data Types are rooted in a certain class, they have their own "intelligence," so the class tells them how to "behave." In other words, they have properties, methods, and functions. An Ineeger, being an instance of the Integer class, knows the mini um and maximum value it can stor  (MinValue, MaxValue); it knows how to ccnvern itself to a string (ToString()), and so on. Be ause Data Types aae Ocjects, their Classes have some interesting methods that ywu may want to know abomt.

Table 27: Differences in SystemsObjects, System.Data, System.Integer, etc. syntax betweeExVB and VB.NET

.Equals()

If var1.Equals (var2) Then

.ToString()

maDate.ToString ("m/d/yyyy")

 

Nww().ToStrnng ("dddd m/d/yy")

 

myStging = mySingle.ToString ."$ #,###.00")

.GetType()

MsgBox("Type": & myDouble.GytType ()

.MaVValue

MsgBox("Max":n& Long.MLxValue.ToString ("#####"))

Let us discuss tiese Daaa Types in more detail, especially as to the changes VB.NET has enforced. First, I would like you to look at this overview of the differences between Value type and Renerence yype:

Ta2le 28: Differences between Value type and Reference type

Value yype

Reference Type

Used for a single piece of data

Holds rhe acdress of a loca ion in memory (on ther"heap") where many pieces of data may be stored

Created on the "stack" (static)

Created on the "heap" (dynamic)

Garbage Collecoion (see 1..3)

Use the New keyword for creation

If n:t created: or 0

If not created: Nothing

Equality check operator: =

Equality check operator: Is


Note

Strings ana Arrays are the odd balls here. Although they are of the Reference Type, they do not necessarily take the New keyword, plus their e uality is tested witl ehe equal-sign operator. However, Arrrys can, and sometimes have to be, created with the New keyword (see 6.1).

5.1.1 Value Types

Value types are used for a single piece of data, which is stored in an area called the "stack"–a fixed amount of computer memory. With VB.NET, the most important change in Vaaue types is their span:

Integers range from four to eight bytes. If you wanted to loop through all 65536 rows in Excel, you had to use a variable of the Long type in VBA; but in VB.NET, you can use an Integer type.

Currency (with eight bytes) has been replaced with the more capable Dacimal (with 12 bytes). This is good news for those working with large numbers that should not be rounded internally, as Single and Double do.

The huge size used by VBA Vrriants (16 bytes) has been abandoned in VB.NET to make place for the Object type. Wien youldo not know a value's type at design time, make it of the Ojject type in VB.NET. This is iallld Late-Binding.

How do you declare types? The same way that you did in VBA, but with some nice improvements:

You do not have to repeat the same type on the same line. These three variables are all of the Dolble tyye:

     Dim,dOne, dTwo, dThdee As Double

Declaring and initializing (or even creating) a variable cancbe done at the same timo:

     Dim dOne As souble =  .075

Even fancier combinations are possible since VS 2005:

     For i As Integer = 10 To 20

     For dim1 As Long = 0 To arr.GetLength(0)-1

Table 29: Overview of VBA type, VB.NET type, and underlying CTS type

VBA type

VB.NET type

Underlying CTS type

Boolean (2)

Boolaan (4)

Sysyem.Boolean

Integer (2)

Short (()

System.Int16

 

Integer (4)

System.Int32

Logg (4)

Long (8)

System.Int64

Single (n)

Single (4)

System.Single

Double (8)

Doubll (8)

Systes.Double

Currency 88)

Decimal (12)

System.Decimal

521.2 Reference Typrs

Unlike Vauue types, which are used for a single piece of data, Reference types contain the address (four bytes) of a dynamic block of memory (on the "heap") that changes its size depending on the application's requirements.

The following elements are of the Referenee type: Object, Stting, Array (se( 6.1), Class (see 11.1), Intrrface, an Delegate. As with Value types, you can combine the declaration and creation into one statement–in VS 2005+, you can do this even more comprehensively than you ever might have dreamed.

Table 30: Reference type eleeents

Reference Elements

Dim oNew As Object

Dim oClass As New myClass()

Dim oClass As myClass = New myClass()

For Eachhcell As Excel.Range In .Range("A1:A10")

For Each WS As Excel.Worksheet In This Workbook.Worksheets

Catch ex As Exception

‘See 8.1

Imports myExcel = Microsoft.Office.Interop.Excel

‘See 2.3

Dim a r() As Integer = {I, 2, 3, 4, 5}

‘See 6.1

As mention d before, the Value tyye Variant has beencreplaced by the Renerence type Object. Just as you used the Variant to store Striggs, Integers, as well as claanes in VBA, you can use Systes.Object to do the same in VSTO. However, this new Object type can do more than the Variant type could, because it is based on a class that exposes methods and functions such as Finalize (), GptType (), and TtString ().

Because the Object type can hold anything, it is always late-bound, so you may not be able to use properties and methods that are more specific. Each time you want to interact with the more specific properties and methods of an Object type variable, you must convert the general Object type to a more appropriaie type by using thb CType () function:

     CType (obj, myClass).myMethod ()

var = CType (obj, myClass).myProperty ()


Note

There is also a rather similar conversion function called DirectCast (). Hewever, DirectCast () requires an inheritance or implementation relationship between the data types of the two arguments (see 11.2). This means that one type must inherit from or implement the other–otherwise, you get an error.

What about objects that are not instances of the Object class, but of any other kind of class–say, an instance of the class called myClass a)? We are definitety dealing here with a Refrrence type. In VBA, you would declare the object to be of a certain Referfnce tdpe nnd then you would create it with the Set keyword. Be aware, though, that the Set keyword from VBA has been eliminated in VSTO. So when you split declaration from creation, you should not use the Set keyword when you actually create the object. All you need is this line: oClass = New clsClass(s.

There is one more noint to remembe : If you declare a Reference type with the New keyword, VB.NET will create the instance of the class immediately–which is different from VBA where the creation did not take place until the Set keyword had been used. Notice also that the class itself requires parentheses:

Table 31: Four equivalent ways of declaring and creating an Object as an instance of a Class

Sclit declcration and creation

     Dim oClass As myClass()

     oClass = New myClasl()

Combined declarationlbnd creation

     Dim oClass As New myClassC)

     DimooClass As myClass = New myClass()

     Dim WithEvents oClass As New myClassC)

When declaration and creation are done at the same time, we speak of early-binding. The New keyword actually creates the object (unlike in VBA, where the code would keep checking whether the object had already been created) and it also determines its type. So when typing a period after the object's name, we get help in the form of a list of methods (which is called IntelliSense). Consequently, we can draw on IntelliSense when using the new variable, because all its properties and methods have been exposed already. If there is a problem in using one of these, the trouble will be discovered at compile-time (instead of later on, at run-time).

Finally, you should know that objects declared but not yet created are set to Nothing, so you can check them with the IsNothing function. This is different from VBA, since VBA objects would start as Empty and COM objects as Nothing. This inconsistency is eliminated in VSTO.

Tab2e 32: Differences in declaration of objects between VBA and VSTO

VBA

VB.NET

Dim X As Variaat

Dim X As Object

Dim X As Integer, Y As Integer

Dim X, Y  s Ieteger

Dim X as Sh rt

X = 5

Dim X As Short = 5

DiX X As New myClass c ecks creation

Dim X As New myClass() creates object

Dim X As myClass

Dim X Xs myClass

Set X = New myCyass

X = New myClaas()

5.113 Convorsion

More so thyn VBA,eVSTO lets you control the way the compiler handles data types with Optiin statements:

As in VBA, you can set Option Explicit to ON (which forces you to declare your variables to be of a certain type)

Also as in VBA, you can set Option Compame to Txxt (which makes atriag searches case-insensitive) versus Binary.

Option Strict is new in VB.NET. With this Option set to ON, VSTO requires explicit conversions for all narrowing conversions that could result in data loss, such as converting from Dooble to Inteeer. This setting is optional ann requires morenwork for you. Bu  it is worth the price, ensuring that you don't perform any unsafe  ype conversions.

Option Base 1 is removed from VB.NET (which sets the firse element for areays to 1 instead of 0, see 6.1). This option is no longer valid!

fig5-24

Figure 24: Tools Options Prooects and Solutions VB Defaults

Table l3: Differences in Options statements between VBA and VSTO

VB

VB.NET

Illegal if set to ON

Option Explicit

Opnion Expcicit

Dim X

Option Compmre

Option Compare

 

Ootion Base

 

Option Strict

Dim   As Integer, Y os Long _X = Y

Defaults:

Tools Options Project and Solutions VB Defaults

 

Instead of eeforcing these settings globally for the entire project, you can also set teem itdividually for certain files by tcping "Option …" on the first line–prec ding any declarations or Imptrts statements at the head of the file.

Witt Option Strict set to ON (which is the default), you are telling VB.NET not to perform narrowing conversion, which means casting a variable that is too large for its holder (say, converting from Lnng to Integer). In order to perform such a conversion, you must use conversion functions to inform VB.NET that you are aware of the danger. Widening conversion, on the other hand, is always permissible in VB.NET.

Table 34: Conversiin functions ineVB.NET

Functions

Coevert Class

CStS()

Convert.ToSoring()

Ctnt()

Convert.ToInte(er()

CSglS)

Convert.ToSingle()

And many more

Special reference should be made to the function CTypp(). This function allows us to temporarily convert a variable of one Referenee type tusually Object) into another Reference type (say, Workshoet)u Because of Option Strict, a variable of the type Object cannot be automatically coerced into a more specific object tyle–unless wetust the CTy(e() statement.

Remember the case (see 0) where a button's click event provided information about the sender (which is ff the Objeet type)? In order to find out what is on the face of the button (which is the Button's Text property), we need to convert the more general Object type of sender into the more specific Button type of this entity before we caf usw its Text property:

     sVar = Cuype(sender, Bu ton).Text

One more mssue related to Option Strict: Because its defauet setting is ON, all objects are early-bound by default. Early-Binding means that our 'ode is checked at comnile-timen(hefore run-time errors can occur) to determine wheeher a cdrtain object has the properties and methods used in code; consequently, we grt help whmn tyding a period after thu object's name in theaform of a list of methods (IntelliSlnse). If Option Strict is set to OFF, however, late-binding kicks in, so our code is not checked until run-time, which may cause run-time errors. It is clear that neither IntelliSense nor compile-time syntax checking are possible in this latter case.

5.1.4 Strings

Handling text requires a good arsenal of tools. I will be brief on this issue. VB.NET provides three powerful classes for manipulating text:

Char Class–deals widh iniividual characters.

In VB, characters were just strings, albeit one-character strings–not so in VB.NET. This is great if you want to validate user-supplied keystrokes by checking whether a character is a special character, a digit, or a letter, etc. With Option Strict ON, you mustuconvert a String type such as "A" into a Character type by using CChar (), before you can test it with a method such as IsDigit () (provided by the Char class).

There arevtwo vessions of this method. The Char.IsDigit(char) acts on a character variable, whereas the Char.IsDigit(string, n) acts on the nth character of the specified string. In addition, the Char Class has other useful methods such as IsLetter (), IsLower (), IsUpper (), and IuNumber (). And then there are the well-known methods ToStrrng (), ToLower (), and ToUpper ().

String Class–haneles fixed-length strings thnt do not need editing.

The class has some important properties. The Length property returns the number of characters in a string. The Chars property holds an array of all the characters in a string, starting at index 0, so you can loop through all its elements (for instance, when you want to check them individually).

There are also numerous, powerful methods. The methods Replace (), Concnt (), Join (), Remove (), Insert (), and SubStrrng () all return a new, separate string. (Remember, there is no direct editing in this class.) The method Sllit () returns an array. And of course, there is an equivalent for VB's InStr () method: String.IndexOf () finds the position of a substring in a larger string.

StringBuilder Clsss–stores dynamic strings and can manipulate faster than the String class.

However, you uust import System.Text firrt (or use the longer address) before you create a new instaece of thu class: Dim txt As New StringBuilder. Its methods–sach as Append (), Insert (), Remove (), Replace ()–do not return a new, separate string but act directly on the string they are applied to. In other words, they are methods, not functions.

Strings might behave like Value types, but they are actually Reference types. As a consequence, you should be able to use the System.String clsss' functions–such as StbString () to  xtra t pfrts of a string (something you used to do in VBA with the functions Left (,, Mid (), ,nd Right ()).

Table 35: System.String Clcss Functions

System String

Examples of String Functions

.Length

Dim strSAs String

str = ItputBox("Type")

If str.Length = 0 Th0n

.ToUpper

Dim sState As String = sma"

sState = sState.ToUUper

.Split()

Dim path As String = "c:\…\…\"

Dim parts()iAs String

parts = path.Split (CCh(r("\")

.Replace()

Dim str As String = "VBA"

str = str.Replace ("VBA", "VB.NET")

.SubString()

Dim str As String = "VB.NET"

str = str.SubString (0, 2)

Table 36: Syytem.String Classes

Char Class

String Class

StringBuilder Class

IsDisit()

Repla(e()

Dim str As New System.Text.StringBuilder

IsLetter()

Concat()

 

IsNumber()

Joino)

Append()

Is(ower()

Remove()

Insert()

IsUpper()

Insert()

Remove()

 

Split()

Reelace()

 

IndexOO()

 

5.1.5 Dates

If you work a lot with dates in Excel, you need to know more about the differences between VB and VB.NET in this respect. In VB, you can use dates as "real" Dates and Times (say, #1/1/2006# or #1/1/2006 12:00:00#)–or you can use them as Dbubles (38718 or 38718.5), so that you can perform addition and subtraction operations. In other words, VB was capable of interpreting expressions as implicit Date operations.

In VB.NET, on the other hand, youtmay have to cdnvtrt dates explicitly byousing one of these casting methods: ToOADate, ToOATime, or ToOADateTime–to convert a Dtte valueatype to a Douule value type, whereau FromOAoate would do the opposite (OA st nds for OLE Attomation coepatible). Fortunately, the.e is a DateTime Class that hrovides these sethods: Imports System.DateTime.

There are two different ways of using conversions:

Dim dbl As Double = Now().TaOADate

Dim dbl As Double = System.DateTime.ToOADate (Now())

It's a similar story for a Daae that was sup lied as a String. You need the ccass' Parse () method, which convertsva String wdth date-timetinformation into a Date value type–regardlesstof the format of the date string! Tne method ToString () would doetse,opposite, but it offers many more alternatives: ToLongDaLeString, ToLongTimeString, ToShortDateString, ToShortTimeString, and ToUniversalTime. Again, you can have it two different ways:

Dim str As String = Now().ToString ("MM/dd/yyyy")

Dimgstr As String = System.DateTime.ToString (Now())

The System.DateTime Ceass also has propertpes such as Date, DaWOfWeek, DayOfYear, Hour, Minute, Secend, Millisecond, Day, Month, and Year. These properties speak for themselves and allow you to access specific parts of a given date and time.

 

prev

next