Chapter 8. Arrays and Collections
Introduction
Visual Basic 2005 makes it very easy to pass arrays and
collections into and out of methods. This makes arrays, collections, and
similar objects very useful for efficiently grouping data. Additionally,
there are some new and useful methods for processing arrays that are
easy to overlook if you’re just moving up from Visual Basic 6.0. Several
recipes in this chapter focus on these methods. For example, arrays have
a built-in Sort()
method that will sort some or all of the
elements in the array, a feature that had to be coded by hand before
.NET.
Generics are also new in Visual Basic 2005, providing a powerful new type-safe way to define collections and other objects such as lists, stacks, and queues. Generics enable compile-time typing of objects without your having to write separate classes for each type you want to support. This chapter demonstrates a simple generic collection. Other chapters provide further examples of generics.
8.1. Filling an Array While Declaring It
Problem
You want to fill an array with starting values without having to explicitly assign each array element individually.
Solution
You can load an array in the
Dim
statement using empty parentheses after
either the array’s name or its type designation, followed by braces
listing the array elements to be assigned.
Discussion
The following line of code creates a one-dimensional array of integers with three elements (elements 0 through 2):
Dim array1D( ) As Integer = {1, ...
Get Visual Basic 2005 Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.