Using Arrays

Team-Fly    

 
Visual Basic .NET Unleashed
By Paul Kimmel
Table of Contents
Chapter 3.  Basic Programming in Visual Basic .NET


Since about 1990, when C++ began gaining popularity, it has been a recommended practice to encapsulate arrays of memory in a class. Storing arrays of data in a class allows the array to perform memory and bounds checking in conjunction with the class and behind the scenes.

Using an unadorned array requires that you manage bounds checking and reallocation of memory (using ReDim). On occasion you may want to use the new array class, but for most new code you will probably find ArrayList easier to use and less error-prone . ArrayList is covered in the section "Working with New Abstract Data Types."

Arrays Are Instances of System.Array

All arrays are instances of System.Array. All members of System.Array were listed in the last chapter in Table 2.10, so we won't repeat that information here. Keep in mind that even simple arrays are classes in Visual Basic .NET.

For additional reference, arrays implement the ICloneable, IList, ICollection, and IEnumerable interfaces.

Declaring Arrays

There are a couple of basic kinds of array declarations. You may declare an array without a fixed number of elements, represented by the empty parentheses (), and optionally include an initializer list. Or, you may declare an array with a fixed number of elements. However, an array with a fixed number of elements specified cannot also have an initializer list.

 Dim StringArray() As String = {"This", "is", "a", "test"} Dim FixedArray(3) As Double 

The size of StringArray is not specified but is indicated by the initializer list {} containing the words This, is, a, and test. StringArray will have four elements indexed from 0 to 3. (Remember that Option Base is not supported, so the first element of a Visual Basic .NET array is 0.)

Note

Remember that Visual Basic .NET does not support the range array using the following syntax:

 Dim A(  low  To  high  ) As  datatype  

FixedArray contains four elements. In Visual Basic .NET, the number of elements is always n +1. FixedArray is declared as FixedArray(3), resulting in four indexable elements from 0 to 3.

Much of the work we used to have to handcraft in VB6 is already implemented in Visual Basic .NET. The next section demonstrates some of the new capabilities of arrays.

Using Array Methods

In addition to array initializer lists, there are many methods that you can take advantage of that make sorting, copying, and finding elements of an array much easier. Many of these methods are Shared methods (refer to Table 2.10 for details). Listing 3.2 demonstrates several array methods.

Listing 3.2 Demonstration of array methods.
  1:  Sub Main()  2:   3:  Dim StringArray() As String = {"This", "is", "a", "test"}  4:  Dim FixedArray(3) As Double  5:   6:  Array.Sort(StringArray)  7:   8:  Dim E As IEnumerator = StringArray.GetEnumerator()  9:   10:  While (E.MoveNext())  11:  Debug.WriteLine(E.Current())  12:  End While  13:   14:  Array.Reverse(StringArray)  15:   16:  E.Reset()  17:   18:  While (E.MoveNext())  19:  Debug.WriteLine(E.Current())  20:  End While  21:   22:  Debug.WriteLine(Array.IndexOf(StringArray, "test"))  23:   24:  Dim NewArray(StringArray.Length) As String  25:  Array.Copy(StringArray, NewArray, StringArray.Length)  26:   27:  Debug.WriteLine(Array.IndexOf(NewArray, "a"))  28:   29:   30:  End Sub 

Lines 3 and 4 repeat the declaration of StringArray and FixedArray from the last section. Line 6 calls the Shared method Sort, passing StringArray as the array to be sorted. After line 6 the strings are ordered as a, is, test, and This. Line 8 declares an IEnumerator interface variable and the enumerator for StringArray is returned. Using enumerators allows you to work with a common interface for enumerating many kinds of data.

The enumerator is positioned before the first element, which makes it convenient to start iterating with MoveNext (see lines 10 and 18). MoveNext returns a Boolean indicating whether or not there is a value at that position. E.Current returns the current element. (Of course you can still use a For loop and an index to iterate over elements of an array, if desired.)

Line 14 sorts the array in descending order with the Reverse method. Again, Reverse is a Shared method, so we pass the array we want reversed as an argument to the method. Line 16 resets the enumerator because we left it pointing past the last element on line 12. Line 22 demonstrates finding an element of an array with the IndexOf method. Line 25 demonstrates copying an array. The number of elements of the source and target arrays must be identical; on line 24 I used the length of StringArray to allocate NewArray. You can also use the ReDim command to resize the target array before copying the array.

Resizing arrays was covered in the section "Resizing Arrays" in Chapter 2.

Multidimensional Arrays

Visual Basic .NET supports multidimensional arrays and nested arrays. A multidimensional array is an array containing a comma-delimited list of array dimensions. A two-dimensional array, for instance, contains two numbers indicating the size of each dimension. Multidimensional arrays are also referred to as matrices.

Chapter 2 demonstrated multidimensional arrays. We won't repeat that information here, but will demonstrate an array of arrays.

We can add any object to the Array type. If we store heterogeneous objects in an array, we can rely on late binding to determine what an element of the array is, or we can perform dynamic type checking and conversion. Because the recommended Option Strict On setting prohibits late binding, I will demonstrate how to convert the elements of the nested arrays to a specific type at runtime. (You also need to know how to perform dynamic type conversions to work with multicast delegates in Chapter 9.)

Note

Late binding refers to the compiler determining the type of an object at runtime. For example, in VB6 we might have defined a variable as a variant and then assigned an object to it with CreateObject. The following Visual Basic .NET code demonstrates a late bound reference to MS Excel with Option Strict Off and replacing the Variant required in VB6 with the Object required in Visual Basic .NET.

 Module Module1   Private Excel As Object     Sub Main()     Excel = CreateObject("Excel.Application")     Excel.Visible = True     MsgBox("Stop")     End Sub End Module 

Early binding is indicated when we add a reference to the object we want to create and declare a variable of that type. An early bound object is an object whose type is known by the compiler at compile time.

Option Strict forces the compiler to do more work and is a recommended setting; thus we give up late bound objects for the benefit of stronger compiler type checking.


To declare an Array object, use the same syntax as any other array and declare the type as Array. Listing 3.3 demonstrates an example with an array defined to contain six elements. To insert a nested array into each indexed position of the array, assign the array object to an indexed position of the containing array. Nested array elements are accessed by indexing the containing array or using an enumerator. To access an element of the nested array, you need to convert the nested array object to a specific type.

Listing 3.3 Nested arrays and dynamic type conversion.
  1:  Sub Main()  2:   3:  Dim StringArray() As String = {"This", "is", "a", "test"}  4:  Dim AnArray(5) As Array  5:   6:  AnArray(0) = StringArray  7:  Debug.WriteLine(CType(AnArray(0), String())(0))  8:  End Sub 

From the listing, you can easily determine that declaring the outer, generic array (line 4) is no different than declaring an array of any type. Assigning StringArray to AnArray(0) nests StringArray into the first element of AnArray. Line 7 demonstrates using dynamic type conversion to get the nested array back to a usable form. The code is packed tightly into a single statement; the next fragment breaks line 7 into a more verbose listing.

 Dim Elem As Object Elem = AnArray(0) Dim Temp() As String Temp = CType(Elem, String()) Dim S As String S = Temp(0) Debug.WriteLine(S) 

Line 7 from Listing 3.3 translates into the very verbose seven lines of code in the preceding fragment. AnArray(0) returns an object. CType converts the Object to a string array. Having the string array, we can access elements of the string array, and finally write the value of the string.

Listing 3.3 demonstrates that it is possible to write convoluted, terse code in Visual Basic .NET. However, the code demonstrates what is possible but not necessarily prudent. Sometimes the data structure can make it very easy to store and manage specific kinds of data. If you find yourself coding nested arrays, hide the complexities of managing the data in a class. As a better alternative, consider using one of the new abstract data types rather than a System.Array.


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