Arrays have undergone a couple of changes in VB .NET. Originally (beta 1) arrays were designed to contain n elements with indexes from 0 to n -1, where n represents the number of elements in the array. The Option Base statement is no longer supported. In beta 2, arrays were reverted back to VB6 Option Base 0 arrays. An array declared as follows Dim A(10) As Type contains n + 1 elements indexable from 0 to n. The sample array contains 11 elements. You can still use LBound and UBound to manage the array bounds, use the Array. GetLowerBound and Array.GetUpperBound methods , or always use the lower bound limit of 0. In addition to changes in arrays, new abstract data types (ADTs), including ArrayList, BitArray, Dictionary, HashTable, Queue, SortedList, Stack, and StringCollection have been added to the System namespace. The Stack class is demonstrated at the end of this section, in the subsection "Abstract Data Types." Collection is defined in the Microsoft.VisualBasic namespace for backward compatibility. (Refer to the section "Abstract Data Types" for more information on Collections.) Range Arrays Not Supported in VB .NET Range arrays aren't supported in VB .NET. VB6 allowed you to define an arbitrary lower and upper bound for arrays, as in the following: Dim I(3 To 5) As Integer The fixed range array notation isn't supported in VB .NET. N-Dimensional Arrays Are Supported Multidimensional arrays are supported in VB .NET. To declare an n -dimensional array, express each dimension as a comma-delimited number indicating the size of each dimension of the array. Keep in mind that each dimension contains n +1 elements. Tip VB .NET supports arrays containing up to 60 dimensions. Dim Doubles(10, 10) As Double The statement declares an 11x11 dimension array of doubles. Arrays are subclassed from System.Array, affording some new capabilities that make array management easier (see "Arrays Are Subclassed from System.Array"). Listing 2.15 demonstrates indexing a two-dimensional array. Listing 2.15 Indexing an n -dimensional array 1: Sub TestArray() 2: Dim Doubles(10, 10) As Double 3: 4: Dim I, J As Integer 5: For I = Doubles.GetLowerBound(0) To Doubles.GetUpperBound(0) 6: 7: For J = Doubles.GetLowerBound(1) To Doubles.GetUpperBound(1) 8: 9: Doubles(I, J) = I * J 10: Debug.WriteLine(Doubles(I, J)) 11: 12: Next 13: Next 14: 15: End Sub The two-dimensional array in Listing 2.15 is indexed in a nested for loop using new methods GetLowerBound and GetUpperBound (lines 5 and 7) on each dimension of the array to make determining arrays bounds much easier. It's preferable to use the new capabilities of the Array class than using older functions like LBound and UBound. Refer to the section "Arrays Are Subclassed from System.Array" for more information. Resizing Arrays As in VB6, arrays can be resized dynamically using the ReDim statement. To preserve existing elements of the array, include the Preserve keyword. The following statement represents resizing the 10x10 array in Listing 2.15: ReDim Doubles(10, 100) Add the Preserve keyword after ReDim and the rightmost dimension values will be saved. If you use Preserve and change any dimension other than the rightmost one, you will get an ArrayTypeMismatchException at runtime. For example, you could write ReDim Preserve Doubles(10, 105) but ReDim Preserve Doubles(5, 100) would raise an ArrayTypeMismatchException at runtime. The code is trying to change the dimension of the array and preserve a dimension that isn't the rightmost dimension. The dimension sized 100 is the rightmost dimension in the example. Returning Arrays from Functions You can return arrays from functions in VB .NET. (This is also supported in VB6.) To return an array, define the return type of the function as an array of type and assign the array variable in the Return statement. (Function results are returned using the Return keyword, as demonstrated in VB .NET.) Listing 2.16 demonstrates returning an array of bytes from the function GetArray. Listing 2.16 Returning an array from a function in VB .NET 1: Function GetArray() As Byte() 2: 3: Dim Bytes() As Byte = {0, 1, 2, 3, 4, 5} 4: Return Bytes 5: 6: End Function 7: 8: Sub TestArray() 9: Dim I As Integer 10: Dim Bytes() As Byte = GetArray() 11: 12: For I = Bytes.GetLowerBound(0) To Bytes.GetUpperBound(0) 13: Debug.WriteLine(Bytes(I)) 14: Next 15: End Sub TestArray calls GetArray on line 10 and the return value of GetArray is used to initialize the local array Bytes on line 10. The GetLowerBound and GetUpperBound methods are used to dynamically determine the upper and lower bounds of the array. (A couple of other new features are demonstrated here: the declarator on line 3 of GetArray demonstrates initialization of the Byte array and line 4 demonstrates how to use the Return keyword. To return the value of a function, simply place the Return keyword where you would have assigned the return value to the function name in VB6.) Arrays come with new capabilities as described in the next section. If you need a dynamically changing array, use the new System.ArrayList ADT. ArrayList allows you to dynamically resize the array by changing the Capacity property. Arrays Are Subclassed from System.Array Arrays are subclassed from System.Array in Visual Basic .NET. Table 2.10 lists the members inherited by Arrays and describes each member. Table 2.10. Members of the Array class Inherited by Arrays Name | Description | Shared Methods | BinarySearch | Uses binary search to find element of one-dimensional sorted array | Clear | Sets a range of elements to Nothing | Copy | Copies range of elements from one array to another | CreateInstance | Creates an array of the specified type and size | IndexOf | Searches a one-dimensional array, returning index of first matching value | LastIndexOf | Finds last index of matching Value | Reverse | Reverses the order of array elements; can be applied to some or all of the array | Sort | Arranges the elements in sorted order | Instance Properties | IsFixedSize | Always returns False unless overridden by subclass | IsReadOnly | Always returns False unless overridden by subclass; indicates ReadOnly status of Array | IsSynchronized | Indicates if array is thread-safe; Always returns False unless overridden by subclass | Length | Returns the number of elements in the array | Rank | Returns the number of dimensions of the array | SynchRoot | Returns a synchronized version of the array for thread-safe access | Instance Methods | Clone | Returns a shallow copy of the array; contained objects are referenced, not copied | CopyTo | Copies elements of one-dimensional array to specified index of target array | GetEnumerator | Returns an IEnumerator (see Listing 2.5 for an example of an enumerator) | GetLength | Returns the number of elements in the specified dimension | GetLowerBound | Returns the lower bound of the specified dimension | GetUpperBound | Returns the upper bound of the specified dimension | GetValue | Returns the value indicated by index arguments | Instance Methods | Initialize | Initializes elements of the array by calling the default constructor; only performs action on ValueType arrays | SetValue | Sets value of array indicated by index arguments | Protected methods and methods inherited from Object aren't listed here. They exist and you can look them up in the help. The most important thing to note is that VB .NET arrays are as easy to use as VB6 arrays, but they come loaded with many additional capabilities. Listing 2.5 demonstrates how to use enumerators (which provide a consistent interface for iterating over elements), and Listings 2.15 and 2.16 demonstrate some of the new capabilities of arrays. Arrays contain one more element than the upperbound value because they are zero-based in .NET. An array Dim A(5) As Integer contains six elements indexed from 0 to 5. It is a good idea to use GetLowerBound and GetUpperBound methods or enumerators to avoid confusion over array boundaries. You will see more array examples in later chapters. Abstract Data Types Visual Basic .NET defines (via the CLR) abstract data types that provide you with a wide variety of storage options for data. VB includes a new ArrayList, BitArray, Dictionary, HashTable, Queue, SortedList, Stack, and StringCollection. Although these ADTs are too numerous to squeeze into this chapter, I will incorporate them in code examples in later chapters where appropriate. Here are some brief definitions: -
Collection is not part of the CLR but was incorporated into the Microsoft.VisualBasic namespace on behalf of VB developers. -
The Collection is defined in the Microsoft.VisualBasic namespace. -
The ArrayList is a smarter array that has built-in dynamic capacity management. -
BitArray represents bits as indexable True and False values indicating the state of the bits. -
A Dictionary provides an abstract class for key and value pairs; the Registry is a physical example of a Dictionary, as are INI files. -
HashTable stores elements by a computed index that makes accessing elements of a HashTable fast and convenient . -
A Queue is a first-in, first-out ADT, or a FIFO, data storage type. SortedList is an ordered list of data. -
A Stack is a last in first out, or LIFO, storage type, and StringCollection is a collection specifically for storing string data. Listing 2.17 demonstrates the basic capabilities of a stack. Stacks are defined to store data and contain simple operations like Push and Pop. Add an element to the top of the stack with Push and take an element from the top of the stack with Pop. Listing 2.17 Demonstration of the basic capabilities of a Stack 1: Sub DemoStack() 2: Dim MyStack As New Stack() 3: 4: Dim I As Integer 5: For I = 102 To 65 Step -1 6: MyStack.Push(I) 7: Next 8: 9: While (MyStack.Count > 0) 10: Debug.WriteLine(MyStack.Pop()) 11: End While 12: 13: End Sub Line 2 instantiates an instance of Stack, defined in System.Collections. The For loop pushes the numbers 102 to 65 onto the stack. The Push operation takes an Object argument, so anything can be placed into the stack. The While loop Pops elements from the stack. If you run the sample code, you will see that the elements come out of the stack from 65 to 102, in reverse of the order in which they were put into the stack. All the collection data types are roughly based on an array of elements; it's the semantic operations that make them convenient for solving one kind of a problem over another. Note Functions and subroutines have changed some in VB .NET. There is enough information on writing procedures that this topic is covered in its own chapter. Refer to Chapter 5, "Subroutines, Functions, and Structures" for more information on this subject. Chapter 5 also covers enumerations. |