Learning the Visual Basic .NET Language - Arrays
(Page 4 of 9 )
Arrays allow you to store a series of values that have the same data type. Each individual value in the array is accessed using one or more index numbers. It’s often convenient to picture arrays as lists of data (if the array has one dimension), or grids of data (if the array has two dimensions). Typically, arrays are laid out contiguously in memory.
Visual Basic programmers will find that arrays are one of the most profoundly changed language elements. In seeking to harmonize .NET languages, Microsoft decided that all arrays must start at a fixed lower bound of 0. There are no exceptions. When you create an array in VB .NET, you simply specify the upper bound.
' Create an array with four strings (from index 0 to index 3).
Dim StringArray(3) As String
' Create a 2 x 4 grid array (with a total of eight integers).
Dim IntArray(1, 3) As Integer
By default, if your array includes simple data types they are all initialized to default values (0, False, or "", depending on whether you are using some type of number, a Boolean variable, or a string). You can also fill an array with data at the same time that you create it. In this case, you don’t need to explicitly specify the number of elements, because .NET can determine it automatically.
' Create an array with four strings, one for each number from 1 to 4.
Dim StringArray() As String = {"1", "2", "3", "4"}
The same technique works for multidimensional arrays, except that two sets of curly brackets are required:
' Create a 4 x 2 array (a grid with four rows and two columns).
Dim IntArray() As Integer = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}
Figure 3-1 shows what this array looks like in memory.

Figure 3-1. A sample array of integers
To access an element in an array, you specify the corresponding index number in parentheses. Array indices are always zero-based. That means that MyArray(0) accesses the first cell in a one-dimensional array, MyArray(1) accesses the second cell, and so on.
' Access the value in row 0 (first row), column 1 (second column).
Dim Element As Integer
Element = intArray(0, 1) ' Element is now set to 2.
One nice feature that VB .NET offers is array redimensioning. In VB .NET, all arrays start with an initial size, and any array can be resized. To resize an array, you use the ReDim keyword.
Dim MyArray(10, 10) As Integer
ReDim MyArray(20, 20)
In this example, all the contents in the array will be erased when it’s resized. To preserve the contents, you can use the optional Preserve keyword when redimensioning the array. However, if you’re using a multidimensional array you’ll only be able to change the last dimension, or a runtime error will occur.
Dim MyArray(10, 10) As Integer
ReDim Preserve MyArray(10, 20) ' Allowed, and the contents will remain.
ReDim Preserve MyArray(20, 20) ' Not allowed. A runtime error will occur.
TIP In many cases, it’s easier to dodge counting issues and use a full-fledged collection rather than an array. Collections are generally better suited to modern object-oriented programming and are used extensively in ASP.NET. The .NET class library provides many types of collection classes, including simple collections, sorted lists, key-indexed lists (dictionaries), and queues. You’ll see examples of collections throughout this book.
Enumerations
An enumeration is a group of related constants, each of which is given a descriptive name. Every enumerated value corresponds to a preset integer. In your code, however, you can refer to an enumerated value by name, which makes your code clearer and helps to prevent errors. For example, it’s much more straightforward to set the border of a label to the enumerated value BoderStyle.Dashed rather than the obscure numeric constant 3. In this case, Dashed is a value in the BorderStyle enumeration, and it represents the number 3.
Here’s an example of an enumeration that defines different types of users:
' Define an enumeration called UserType with three possible values.
Enum UserType
Admin
Guest
Invalid
End Enum
Now you can use the UserType enumeration as a special data type that is restricted to one of three possible values. You assign or compare the enumerated value using the dot notation shown in the following example.
' Create a new value and set it equal to the UserType.Admin constant.
Dim NewUserType As UserType
NewUserType = UserType.Admin
Internally, enumerations are maintained as numbers. In the preceding example, 0 is automatically assigned to Admin, 1 to Guest, and 2 to Invalid. You can set a number directly into an enumeration variable, although this can lead to an undetected error if you use a number that doesn’t correspond to one of the defined values.
In some scenarios, you might want to control what numbers are used for various values in an enumeration. This technique is typically used when the number has some specific meaning or corresponds to some other piece of information. For example, the following code defines an enumeration that represents the error code returned by a legacy component.
Enum ErrorCode
NoResponse = 166
TooBusy = 167
Pass = 0
End Enum
Now you can use the ErrorCode enumeration, which was defined earlier, with a function that returns an integer representing an error condition, as shown here:
Dim Err As ErrorCode
Err = DoSomething()
If Err = ErrorCode.Pass
' Operation succeeded.
End If
TIP Enumerations are widely used in .NET. You won’t need to create your own enumerations to use in ASP.NET applications, unless you’re designing your own components. However, the concept of enumerated values is extremely important, because the .NET class library uses it extensively. For example, you set colors, border styles, alignment, and various other web control styles using enumerations provided in the .NET class library.
Next: Variable Operations >>
More Visual Basic.NET Articles
More By Apress Publishing
|
This article is excerpted from chapter three of the book Beginning ASP.NET in VB.NET: From Novice to Professional, written by Matthew MacDonald (Apress, 2004; ISBN: 1590592786). Check it out at your favorite bookstore today. Buy this book now.
|
|