The Collection Object VB.NET

VB .NET implements a special object called the Collection object that acts as a container for objects of
all types. In fact, Collection objects can hold other objects, as well as nonobject data.
In some ways, the Collection object is an object-oriented version of the Visual Basic array. It supports
the following four methods:

Add

Adds an item to the collection. Along with the data itself, you can specify a key value by which the member can be referenced.

Count

Returns the number of items in the collection.

Item

Retrieves a member from the collection either by its index (or ordinal position in the collection) or by its key (assuming that a key was provided when the item was added to the collection).

Remove

Deletes a member from the collection using the member's index or key.

For example, the following code defines a collection object named colStates to hold information about U.S. states and then adds two members to it, using the state's two-letter abbreviation as a key:

Like members of an array, the members of a collection can be iterated using the For Each...Next construct. Also like arrays, collection members are accessible by their index value, although the lower bound of a collection object's index is always 1.

Arrays and collections each have advantages and disadvantages. Some of the advantages of collections over arrays are:

  • New collection members can be inserted before or after an existing member in index order. Moreover, indexes are maintained automatically by VB, so we don't need to adjust the indexes manually.
  • Collection members can be referenced by key value. This feature makes collections similar to associative arrays (which are used by languages such as Perl).

Note that when deleting collection members by index, it is important to iterate though the indexes inreverse order because member deletion changes the indexes of other members.


Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

VB.NET Topics