Vb.net Arrays
Vb.net Arrays
Return False
Catch E As Exception
Console.WriteLine("An error occurred: {0}", E.Message)
Return False
Finally
'dereference the object for this demo
myArray = Nothing
End Try
End Function
Arrays
Few programming topics are as important, and as deserving of discussion, in a core reference book as arrays.
Every programmer, no matter the project, will use an arraya data structure for managing collections of
identical data types, such as integers, characters, strings, and even custom reference types. The array is to the
programmer what the chisel is to the carpenter or the scalpel is to the surgeon.
Arrays find themselves in all algorithmseven ASP.NET applications, Web services code, and various
components along the data supply, storage, and retrieval route. This section thus presents not only an
introduction to arrays, but also advanced topics, such as how to use arrays, insert values into them, sort them,
search them, and put them to work. We will also build on Chapter 7's discussion of how arrays can be passed
to methods and how methods can return arrays. This will not be the only chapter in which arrays and array
usage will crop up. Later chapters present some sophisticated techniques and algorithms that require array
implementation and access.
An array is a collection of objects of the same type, conveniently packaged in an indexed, sortable, and
searchable construct. The structure itself, which derives from System.Array, is a collection of objects (as
mentioned earlier, it implements ICollection) that are referenced via the container's name and an index
location.
One of the main attractions of arrays is that their elements, the values they hold, can be randomly accessed. As
you saw, this was not possible with the Stack and Queue classes, which also do not allow you to insert at a
certain location or remove at a certain location.
Figure 12−3 provides a representation of an array. It has a "bottom" and a "top." The array can grow and
shrink. You can copy the array, reference any element in the array, sort the array, search the array, reverse the
elements of the array, and much more.
376
The Array Class
it is a zero−based structure. The zero element is also known as the array's zeroth element, or lower bound
element(or LBound) element. An array cannot have zero length; there is always at least one element, which is
the zeroth index, as illustrated in Figure 12−3.
Not all variables referenced in the array are referenced in the same way. String objects, for example, are
referenced by references to the string data (in other words, the array's string elements are just references to the
string objects), while numeric data is stored directly in the array (see the "Boxing" section in Chapter 8).
The elements of an array and its contents can be accessed or referenced through the index (see Figure 12−4),
which would be like punching a hole in the stack or queue to access an element's value in the body of the
structure instead of at one of the ends.
Figure 12−4: Arrays are underpinned by an index, also known as a subscript, which gives you direct and
random access to any element in the array
You refer to the element of the array as the element type. The element type is created when you create the
array, and destroyed when the array is destroyed. Naturally, the only type that cannot be the element of the
array is the array itself.
Note As demonstrated in the earlier queue example, CopyToArray, an array can be declared as
type Object and then upcast to another type later.
Arrays can also comprise more than one dimension, and the elements in the dimensions can be referenced
separately from the elements of the surrounding dimensions, as we will see later in this chapter.
All arrays derive from the base class System.Array. This includes the Length property. The class contains a
number of useful methods and properties, which are listed alphabetically in Table 12−4.
Table 12−4: The Members of System.Array (Excludes Members Inherited from Object)
377
Declaring and Initializing Arrays
When you create an array, you need to declare a length for each of its dimensions. The length of the array is
the number of elements that you need to store. As you now know, .NET array elements (no matter the
language) are referenced through a zero−based index, which, as mentioned earlier, means the first element of
the array is given the index value 0. So, to specify the length of the array, you defer to the range of indices
counting from and including 0.
Arrays are declared in the same manner as you declare any variable. Visual Basic array grammar includes
parentheses or brackets after the data type (as opposed to square brackets used by other languages). In the
following example, an array reference variable called sAlarms is declared, the intention of which is to
reference an array of ordinal values:
If you need to declare an array reference variable that will reference Double value types, you could declare
the array reference as follows:
How many values can either of the preceding arrays hold? Tip: While they are declared as arrays of ten
elements (0 to n−1), you'll be surprised to discover that you won't get ten. The Visual Basic architects did
something here that confuses a lot of programmers. Using the ForNext iteration structure (discussed in the
previous chapter), let's find out what gives:
378
Declaring and Initializing Arrays
Dubug.WriteLine(intI)
Debug.WriteLine(injectorAlarms.Length)
End Sub
Holy mackerel! The injectorAlarms array has 11 values (0 to n−2). Talk about getting what you didn't ask
for. (What's worse is that intI after the For loop ends up at 12 (because it started at 0).) Why did the VB
architects do this? To make it easier to convert from the 1−based arrays supported in the classic versions of
Visual Basic (version 6 and earlier), under the covers, the Visual Basic implementation of the .NET arrays
tacks on the zero element and thus adds one more element to the declaration of, in this case, 10.
When you convert a Visual Basic 6 or earlier array, you get the extra element over and above (or would that
be "under and below"?) the original array lengthin the zeroth position. The problem is that C# and other .NET
languages do not work that way. The same declaration in C# produces a ten−element array (0−9). To thus
declare arrays to the exact length you specify in the declaration, you can use the following kluge code:
It's not elegant but it will do until Visual Basic's array declaration works like C# or J# declarations, or we get
a new array class that's not as confusing (or you take the bold step of creating a new array class from scratch).
The preceding lines of code thus declare the array reference variable named injectorAlarms with the
"potential" to hold 11 Integer or Double values. In other words, the preceding code does not yet lead to the
creation of the actual object. The object gets constructed implicitly at the attempt to assign variables to the
declared elements and when you call New in the declaration. This means that we can create the array
reference variable but delay initialization and activation of the array object, a tactic you can get away with
when you set Option Explicit to Off to allow implicit typing declaration.
The constant between the parentheses does not have to be a number. Any legal means of obtaining the
constant will do; even a value in a queue will work, as demonstrated here:
The array reference variable should not be confused with the array element values, which are also variables
(of types). The array variable is really nothing more than a reference to an array object, as you will learn about
in the following chapter.
To initialize the array object in the declaration of the reference variable, you need to call the New constructor.
The following example creates the array object Alarms to hold four Integer variables (in elements 0 through
3):
What does this code do? As you are aware, an array in .NET is an object that derives from System.Array.
The New operator thus accesses the constructor of the array class and passes the argument to create the array
of five elements. The array can thus be illustrated as in Figure 12−5.
379
Declaring and Initializing Arrays
Note In case you were wondering, the Visual Basic 6 syntax of specifying lower bound to upper bound
elements, such as Dim Days(1 to 20) As Integer is no longer supported in Visual Basic .NET.
If an array is an object, then assigning the object to another reference variable shouldn't be a problem. This
can be done if you leave off the parentheses with an assignment statement, as follows:
oAlarms = sAlarms
Both reference variables reference the same object, as illustrated in Figure 12−6.
To recap, first declare the array, add an equal sign, and then follow the equal sign with the list. (You can also
leave out the New keyword, and the compiler will implicitly make the call. If you make the call to New,
however, you must include the pair of curly braces on the end of the statement, even if the pair is empty.)
The number of elements in the array can be accessed by the Length property of the array. You can test these
array declarations using the Length property. Here's an example:
380
Declaring Multidimensional Arrays
This is a rectangular array that has two dimensions. You can think of the array as a table with columnseach
column represents the dimension, as illustrated in Figure 12−7.
The first mdArray declaration creates a two−dimensional array that is not initialized with values. The second
mdArray1 declaration creates an array of three dimensions.
Note When calling the Ubound function on a multidimensional array, omitting the dimension returns the
upper bound of the first dimension.
Knowing the rank of an array is not important until you need to work with more than one array and need to
convert from one array to another. See the discussion of ArrayTypeMismatchException in the "Array
Exceptions" section later in this chapter.
Jagged Arrays
A jagged array is an array of more than one array, or an array of arrays. It is useful for working with
two−dimensional data where the structure is not rectangular, as in a multidimensional array. Imagine
declaring two arrays, sticking them together, and then referencing them through a single reference variable.
Each array can be a different length and have multiple dimensions. The shape of such an array is jagged rather
than rectangular or square. The jagged array is illustrated in Figure 12−8.
381
Programming Against Arrays
After the jagged array is initialized, you can access the elements in either member array using code,
demonstrated as follows:
Jagged arrays are not as universal or powerful in utility as single arrays. Many .NET constructs do not (yet)
know how to access a jagged (and even multidimensional) array. Two good and familiar examples are the
CopyTo and ToArray methods, discussed earlier. You typically need a lot of funky code to get a good
system going against the collection of arrays, and you might be better off just creating an array of objects, as
discussed later in this chapter.
First, we need to get data into the arrays before they can be of much use. You can populate the array elements
by referencing the index value that represents the position in the array. This is done as follows:
sAlarms(0) = 14320
sAlarms(1) = 12390
sAlarms(2) = 14870
sAlarms(3) = 14975
Arrays are simple to work with, although they do have their nuances, as we will see shortly. The initial value
of an array is Nothing. In other words, in the sAlarms declaration shown earlier, each element of the
five−element array is Nothing. Referencing the Nothing literal is not impossible, as the following code
shows:
382