1. Computing

Using Arrays and Collections in VB.NET

From , former About.com Guide

1 of 6

Arrays and Collections: The next best thing to a database!
Arrays and Collections

Arrays and Collections

A thorough understanding of Arrays and Collections is a key difference between the "Hello World" level of programming and higher levels of ability. There is a huge world of tricks and techniques that we can use once we understand this part of VB.NET.

The subtitle of this lesson, "the next best thing to a database" is actually only partly true. You can get an idea about what a database does by studying how arrays and collections are used, but they're really targeted at different requirements. A database is for storing huge amounts of information where the relationships between things are critical.

(Here's an example of a "relationship". If "automobile" is one type of data in the database and "person" is another, then "person owns automobile" is a relationship. Describing relationships like that is difficult - but not impossible - with arrays and collections.)

Arrays and collections are great for simply storing and retrieving sets of information. If your application just needs a list of automobiles, this is the way to go.

The main design pattern used with arrays and collections is iterative processing, that is, program loops. Arrays are usually processed with a For-Next or Do Loop that changes the index to process all the elements:


Dim i As Integer = 0
Do Until i > 10
    If Not StringArray(i) = "" Then
        Console.WriteLine(StringArray(i))
    End If
    i += 1
Loop

One type of loop, For Each, is designed just for collections. Normally, each element in an array or collection will be processed in the same way. For example, a collection of newly manufactured automobiles might need to be updated to assign a factory recommended price. (The price would probably be a property of an "Automobile" object.) Iterating through a collection using For Each is called enumeration. So if you read something like, "This article describes a method for enumerating ..." (copied directly from a Microsoft support page), you know that they just mean, "process each element of a collection with a For Each loop.

On the next page, we consider a common example of a For-Each loop used with a collection: the collection of controls in a Windows Form.

©2013 About.com. All rights reserved.