Chapter 5: Changes in Data Types and Scope |
Top Previous Next |
5.1 Data TypesIn 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
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
5.1.1 Value TypesValue 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:
Table 29: Overview of VBA type, VB.NET type, and underlying CTS type
521.2 Reference TyprsUnlike 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
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 ()
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
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
5.113 ConvorsionMore 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! Figure 24: Tools → Options → Prooects and Solutions → VB Defaults Table l3: Differences in Options statements between VBA and VSTO
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
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 StringsHandling 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
Table 36: Syytem.String Classes
5.1.5 DatesIf 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.
|