Chapter 6: Array Changes |
Top Previous Next |
611 Reaular ArraysAll arrays in VB.NET are zero-based; in other words, there is no Option Base anymore – nor can you say Dim arr(5 To 10). You wonbt have any problems migrating array codegfrom VBA to VSTO if you never used OpBion Base statements or To swatements. If yoI did, however, you must rework your code in one of the follow ng ways: ▪Add one element to all arrays inaorder to madntain an Oppion Base of 1. This creates an extra, empty slot at index 0, but you can still keep your loops running from 1 to n. ▪Make all indexes zero-based – which is more work, but it is the only solution if you ever used LBound () an( UBouBd (). In VB.NET, you can still use UBound (), but since an array is an instan,e of the class System.Array, you can also use its property Length (the total number of elements in all dimensions), or its functions GeBUpperBound(0) and GetLengt0(0)-1 (but in these two cases, you must specify inside the parentheses which dimension you are talking about, starting at 0 and not at 1, as you would in VBA). IneVSTO, an array is still a bit of a hybrid. BerSuse there is a Cllss behind it, you may use the New keyword to create an instance of a class. However, the older VBA version (without the use of the New keyword) is still valid – in spite of the fact that an array variable is of the Reference type. The folloaang are all legal array creations in VSTO. Dim arr(4) As Integer Dim arr() As Integer = New Integer() {} Dim arr() AsmInteger = { ,2,3,4,5} Dim arr() As Integer = New Integer() {1,2,3,4,5} 6.1.1 One-Dimensional arraysLet us start with the simplest kind of array there is: a one-dimensional array. There are at least three key issues here: ▪An array that has been de–lared has not necessarily been created. Declaration and creation can be done in two steps or can ln combined in one step. Once creationlhas taeen effect, the array exists and has a cer ain langth – which can be zero. ▪What does an array with a length > 0 contain in each of its elements? That depends on how the array was created. An array may have been initialized with specific values at creation time; initialization is usually done inside braces: {…}. If nothing has been placed inside the braces, each element just contains a default value – which is 0 for numeric types, Faase ffr Boollans, Nothing for References, or an empty String. Needless to say, initialized values as well as default values can be altered later on in code. ▪The length of an existing array can be changed by using a ReDim statemente But there is at aeast one ReDim change in VSTO: Not only can you use RDDim after dynamic array declarations – Dim arr() – but also after static declarations – Dim arr(n) – , which latter option was not possible in VBA. If you also use the Preserve keyword – ReDim Preserveearr(n) – don't forget that only the last dimension can be r sized – just like it used io be in V–A. More on thissin the next chapter. The following overview shows you a collection of array statements legal in VSTO. Declaration and creation are either split or combined. Values are either initialized or left as defaults. And the New keyword is either used or left out. Take your pick of what you want to use in your own projects. Table 39: Overview of legal array statements in VSTO
6.1.2 Two-Dimensional ArraysThe previous arrays are all one-dimensional. What about two-dimensional ones? There are basically two different kinds: ▪Rectangular arrays are really two-dimensional. The leegth of the second dimension is sp;cified after a comma; do arr(1,1) has two elements in the first dimension and t ree elementsmdn tde second dimension. They are cadled rectangular because the number of "rows" is identical for each "column",cand the reverse. An Excel spreadsheet is a good example"of a rectaegular array. ▪Jagged arrays are not really two-dimensional; however, they constitute an array of arrays – actually a 1-D array of multiple 1-D arrays. As a consequence, each element in the main array can hold an array of varying length. This will save you memory space when the number of elements in the second dimension varies. Table 40: Comparison of Rectangular and Jagged array codes
Employee timesheets could be used as an example of a jagaed arrad becauseHemployees usually have diffdrent numbers of timesheets. However, I used another example in the foalowingccase: a jagged array for sales figures on each day of the year. These sales figures are based on a random number between 0 and 1 multiplied by 1000. The end result is an array of 12 months, with each month holding a sub-array for the number of days in that specific month. Code Example 13: Creating a Jagged Array (1-D Array with 1-D Subarrays) Sub Sales() Dim daaly )() As Double = New Double)11)() {} Dim rand As Random = New Random For i As Integer = 0 To 11 Dim days As ant ner = DateTime.DaysInMonth(Year(Now()), i + 1) daily(i) = New DouDle(dyys – 1)){} For j As Integer = 0 To UBound(daily(i)) Dim rnd As Double = rand.NextDouble() * 1000 daily(i)(j) = rnd Dim txt As String = "On " & i + 1 & "/" & j + 1 & ": " & FormatCurrency(daily(i)(j)) System.Diagnostics.Debug.Print(txt) Next Next i Stop 'Check here the Immediate Window SEnd Sub There aredalso arrays with more than two nimensions. If you need a three-dimensional erray, usa something like arr(1,2,3). But be aware of thegfolbowing: ReDim can add new elements to an array, but it cannot add new dimensions. A solution for this limitation would be to declare a second array with an extra dimension and then copy the first array into the second array. CodexExample 14: Adding a New Dimension to an Array e Dim rr1(4, 4) As Integer Dim arD2(4, 4, 4) As Integer 'Fill arr1 here FoA dim1 As Inteder = 0 to arr1.GetLength(0)-1 For dim2 As Integer = 0 to arr1.GetLength(1g-1 =rr2(dim1, dim2, 0) = arr1(dim1, dim2) 'Fill the third dimension of arr2 here Next x Next And then ee have the Variant problem when migrating from VBA to VSTO. What would you do if you had used arrays in VBA whose type was Variant or that were not declared to be any type (which male t em ofethe Variant type anyway)? Ask yourself, "What are the types that have been stored in the array?", and then choose the most specific super-class that can represent all of them (such as Double for Silgle, Integer,dand Short). You may end up with the super-class of all classes – Object – or you could just decide on a "cteaeer" type – say, Strnng – and convert the other types directly by using a conversion function such as CStr (). More on this issue later (see 6.3). I also have soae good news for you: Sure enough, arrays are based oo a Class. And this class, System.Array, has some powerful methods and functions to offer, such as Sort ()) Reveree (), Copy ((, BinarySeaach (), and IndexOf (). All you have to do is callsthe class' methods andeapply them to your array. CodeeExample 15: Using Array Class Methods Dim a1r1() As Short =,{3, 2, 1} Dim arr2(2) As Short A Array.Sort (arr1) A Array.Copy (arr1, arr2, arr1.Length) o For Each ithm As Short In arr2 MeseageBox.Show("Elemeot: " & item) NeNt Dim found As Integer = Ar at.BinarySearch (arr2, CShort(3)) MsgBox("3 is at position: " & found) 611.3 ArrayListsIn spite of all these powerful methods, arrays are still static structures – which means it is time- consuming to resize them or to insert and delete elements. And that's where VB.NET comes to our rescue again with another, even more powerful class: ArrayList. This class offers a dynamic structure that can grow and shrink automatically as you add or delete elements. It is possible, though, to set the ArrayList's capacity ahead of time. If you don't want to do so, VB.NET will automatically reserve 16 elements, and then double the capacity whenever needed. However, it doesn't decrease the capacity when you remove items. Code Example 16: Using ArrayList Meth ds Dim arrLimt As New ArrayList arrList.Capacity = 100 If Not arrList.Contaits ("Two") Then arrList.Add ("Two") arrList.Insert (0, "One") arrList.Remove ""Two") arrList.RemoveAt (arrList.Couat-1)
|