0% found this document useful (0 votes)
3 views

Vb.net Arrays

The document provides an in-depth overview of arrays in programming, emphasizing their importance for managing collections of identical data types. It covers various topics including array declaration, initialization, and advanced operations such as sorting and searching. Additionally, it introduces multidimensional and jagged arrays, highlighting their unique characteristics and use cases.

Uploaded by

srenevasan05
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Vb.net Arrays

The document provides an in-depth overview of arrays in programming, emphasizing their importance for managing collections of identical data types. It covers various topics including array declaration, initialization, and advanced operations such as sorting and searching. Additionally, it introduces multidimensional and jagged arrays, highlighting their unique characteristics and use cases.

Uploaded by

srenevasan05
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

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.

Figure 12−3: A simple one−dimensional array


The array is referenced with a reference variable (see Chapter 9 for more details on referencing objects), and
you use it to store and retrieve variables of a like type, the elements of the array. The values are stored,
retrieved, and manipulated by referencing the indexor subscriptof the array element (the slot or pigeon hole in
which array objects are "logically" stored). The first element in the array is indexed at number 0, which means

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.

The Array Class

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)

Class Member Purpose


BinarySearch Searches a one−dimensional array for a value
Clear Sets a range of elements to zero, null, or False in a one−dimensional array.
(See also "The Erase Statement," later in this chapter.)
Copy Copies the entire array or a range of elements in a one−dimensional array to
another array
CopyTo Specifies the starting element to copy to in the target array
CreateInstance Represents alternative array creation syntax for late binding
GetEnumerator Returns an instance of the IEnumerator implementation

377
Declaring and Initializing Arrays

GetLength Returns the length of a dimension


GetLowerBound Returns the lower bound element of a dimension
GetUpperBound Returns the upper bound element of a dimension
GetValue Returns the value at a specified index in any dimension
IndexOf Returns the index at the first occurrence of the value searched for
Initialize Not yet implemented
LastIndexOf Returns the index at the last occurrence of the value searched for
Reverse Reverses the elements in a one−dimensional array
SetValue Sets the value at the specified index in a one− or multidimensional array
Sort Provides built−in sort operations
IsFixedSize Returns True or False if the array size is fixed
IsReadOnly Returns True or False if the array is read−only
IsSynchronized Returns True or False if the array is synchronized (thread−safe)
Length Returns the length of a one−dimensional array
Rank Returns an ordinal representing the number of dimensions in the array
SyncRoot Returns an object used to synchronize access to the array
Note Table 12−4 does not include the members inherited by System.Array, such as GetType and ToString.
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:

Dim injectorAlarms(10) As Integer

If you need to declare an array reference variable that will reference Double value types, you could declare
the array reference as follows:

Dim latinumPercentages(10) As Double

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:

Public Sub OffByTwoArrays()


Dim injectorAlarms(10) As Integer
Dim intI As Integer
For intI = 0 to injectorAlarms.Length
Next intI

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:

Dim latinumPercentages(10 − 1) As Double

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:

Dim latinumPercentages(ArrayQueue.Dequeue) As Double

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):

Dim Alarms() As Integer = New Integer(4) {}

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

Figure 12−5: The array injectorsAlarms is a five−element array


In addition to the creation or activation of the array object with New, the array object must be initialized with
the trailing curly braces (the same idea is used in C# and Java). You cannot leave out the curly braces, because
that will generate an error, but you can leave the pair of braces empty, as illustrated in the preceding code, or
use the curly braces to provide the initial variables for the array elements, as demonstrated in the next section.

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.

Figure 12−6: oAlarms and sAlarms refer to the same object


Note The Object Reference Model is discussed in Chapters 8 and 9.
To initialize the array object with data, use a comma−separated list between the curly braces, as follows:

Dim sAlarms() As Integer = New Integer () {1, 2, 3, 4, 5}

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:

Debug.WriteLine("There are {0} elements in sAlarms", sAlarms.Length)

Behold, sAlarms is truly one element larger than you declared:

There are 11 elements in sAlarms

380
Declaring Multidimensional Arrays

Declaring Multidimensional Arrays


You can use a multidimensional array to reference elements in more than one dimension. The construct is well
suited for simple referencing of two−dimensional data, much like a spreadsheet. To declare an array of more
than one dimension, use the following syntax:

Dim sAlarms(4,4) As String

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.

Figure 12−7: A multidimensional array of two dimensions


The number of dimensions declared in an array determines the rank of the array. An array of one dimension
has a rank of 1; an array of three dimensions has a rank of 3, and so on. You can't go nuts with dimensions,
either, because arrays are limited to 32 dimensions. The following syntax for declaring multidimensional
arrays is acceptable to the .NET runtime:

Dim mdArray(,) As Integer


Dim mdArray1() As Integer = {New Integer(), New Integer(), New Integer()}
Dim mdArray2(,,) As Integer = New Integer(5, 5, 5) {}
Dim mdArray3(,) As Integer = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}

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

Figure 12−8: The jagged array


Declaring, initializing, and working with the jagged array can be tricky. The array illustrated in Figure 12−8
comprises two arrays, which can be declared as follows:

Dim sAlarms(2)() As Integer


Dim sAlarms()() As Integer = {New Integer() {5, 6, 7}, _
New Integer() {10, 24, 63, 82}}

After the jagged array is initialized, you can access the elements in either member array using code,
demonstrated as follows:

Dim sAlarms()() As Integer = {New Integer() {5, 6, 7}, _


New Integer() {10, 24, 63, 82}}
Dim intI As Integer
For intI = 0 To UBound(sAlarms(1))
Console.WriteLine(sAlarms(1)(intI))
Next intI

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.

Programming Against Arrays


This section deals with the peculiarities of Visual Basic arrays and demonstrates usage of several important
methods of System.Array and a number of stand−alone keywords and statements, native to the Visual Basic
language, created to make working with arrays easier. The legacy array−handling keywords can be accessed
via the Microsoft.VisualBasic.Information namespace.

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

You might also like