In VB, an array??™s lower bound is always 0 in order to meet the Common
Language Specification (CLS) restriction that arrays have a 0 lower bound. The upper bound
for array1 is 5, as stated in the code, making for an array with 6 elements. Notice the use of the
New operator to allocate the array1 and array2 instances. The omission of New to allocate the
array3 instance is a notational shortcut.
One convenience of .NET arrays is that they are range-checked. If you step off the end of
one of them, going out of bounds, the runtime will throw an IndexOutOfRangeException.
You can iterate through the elements in the array using a For . . . Each statement. This
works because System.Array implements IEnumerable. The section titled ???How Iteration Works???
describes IEnumerable and its cousin IEnumerator in more detail.
Type Convertibility
When you declare an array to contain instances of a certain type, the instances that you may
place in that array can actually be instances of a more derived type. For example, if you create
CHAPTER 10 n ARRAYS AND COLLECTIONS 198
an array that contains instances of type Animal, then you can feasibly insert an instance of Dog
or Cat if both of them derive from Animal.
You can also coerce array types in this other, even more interesting way:
Imports System
Public Class Animal
End Class
Public Class Dog
Inherits Animal
End Class
Public Class Cat
Inherits Animal
End Class
Public Class EntryPoint
Shared Sub Main()
Dim dogs() As Dog = New Dog(3) {}
Dim cats() As Cat = New Cat(2) {}
Dim animals() As Animal = dogs
Dim moreAnimals() As Animal = cats
End Sub
End Class
The assignment from dogs to animals and from cats to moreAnimals is something that
you can do as long as their ranks match and the contained type is convertible from one to
the other.
Pages:
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332