1. Technology

Using Arrays and Collections in VB.NET


5 of 6

Collections: When Your Data is an Object
Using Arrays and Collections in VB.NET

List(Of T) Versus Collection

Collections fit perfectly with the Object Oriented Programming concepts that VB.NET uses. If everything in VB.NET is an object (and that's true), then it's possible to put anything in VB.NET into a Collection (and that's true too).

Let's continue to use the example from the first step, Automobile, as an object. If we define a collection of automobiles, then the objects could have a property called "Color" and a methods called "Brake" and "Accelerate". (Better have both, not just one!)

If your program was a control program for an automobile assembly plant, this could be a very realistic example. One program might control an automated painting process in the plant (which would use the Color property for each Automobile object) and another program could control an automated test facility (using the Brake and Accelerate methods). Once you start to think like this, you realize that just about everything in the real world can be described as objects. (Details about how to code classes with different properties and methods can be found in other About Visual Basic articles, such as the Visual Basic .NET 2010 Express tutorial.)

Wherever you use an array, it's possible to use a collection instead. But there are a number of different types of collections that might be used and they're quite different. Just one namespace, the System.Collections namespace in Framework 4.0, lists thirteen different collection classes from an ArrayList to a Stack. The class that is actually named "Collection" isn't even part of the usual VB.NET collection namespaces; it's in the Microsoft.VisualBasic namespace instead. (This namespace contains classes designed specifically to support compilation and code generation using VB rather than, for example, C#.) Two types of collections are the List(Of T) collection and the Collection collection. List is zero based while a Collection is one based. The illustration proves it.

Actually, Collection does have a zero element internally, but it's not used. Collection is an example of an "untyped" collection. That means that you can save different types in it.

Dim aCollection As New Collection
aCollection.Add("A String")

The problem is that this opens the door to data exception errors when you use the collection. Your program will require a lot more validation and exception code. Typed collections - like List(Of T) - are recommended instead.

  1. About.com
  2. Technology
  3. Visual Basic
  4. Learn VB.NET
  5. Using Arrays and Collections in VB.NET

©2014 About.com. All rights reserved.